'\0' not accepted as an empty "const char *": is this a compiler problem or not?

Mojca Miklavec mojca at macports.org
Mon Jun 20 23:21:06 PDT 2016


Hi,

When I tried porting some software (originally written for Windows and
now asking for C++14) to MacPorts I was stuck with an external piece
of a code written in C, compiled with C++ (I don't fully understand
why it is compiled with C++, but I cannot change that).

This is a minimal example that fails:

    void test(const char *a) {}
    int main()
    {
        test('\0'); // pass an empty string
        return 0;
    }


A relatively recent clang++ compiler just throws a warning (using libstdc++):

> clang++-mp-3.7 test-dev.c
clang: warning: treating 'c' input as 'c++' when in C++ mode, this
behavior is deprecated
test-dev.c:5:10: warning: expression which evaluates to zero treated
as a null pointer constant of type 'const char *'
[-Wnon-literal-null-conversion]
    test('\0');
         ^~~~
1 warning generated.


But the same compiler in C++11 or C++14 mode throws an error:

> clang++-mp-3.7 -stdlib=libc++ -std=c++14 test-dev.c
clang: warning: treating 'c' input as 'c++' when in C++ mode, this
behavior is deprecated
test-dev.c:5:5: error: no matching function for call to 'test'
    test('\0');
    ^~~~
test-dev.c:1:6: note: candidate function not viable: no known
conversion from 'char' to 'const char *' for 1st argument
void test(const char *a) {}
     ^
1 error generated.


GCC doesn't seem to care though:

> g++-mp-4.9 -std=c++14 test-dev.c
> # no warnings or errors


I didn't test on Windows. I installed clang 3.5 on Linux (the latest
version shipped by Debian-based Mint) and the results were the same as
on Mac:

> clang++-3.5 -std=c++11 tes-dev.c
clang: warning: treating 'c' input as 'c++' when in C++ mode, this
behavior is deprecated
test-dev.c:4:5: error: no matching function for call to 'test'
    test('\0');
    ^~~~
test-dev.c:1:6: note: candidate function not viable: no known
conversion from 'char' to 'const char *' for 1st argument
void test(const char *a) {}
     ^
1 error generated.

> clang++-3.5 test-dev.c
clang: warning: treating 'c' input as 'c++' when in C++ mode, this
behavior is deprecated
test-dev.c:4:10: warning: expression which evaluates to zero treated
as a null pointer constant of type 'const char *'
[-Wnon-literal-null-conversion]
    test('\0');
         ^~~~
1 warning generated.

I came up with a workaround, defining

   const char *empty = "";
   test(empty);


The upstream developers replied:

first:
> If I'm understanding correctly, it also seems like a bug in the C++
> compiler to think that a character constant is not const,

second:
> If I understand the patch well, the C code supplies a character \0
> when an empty string is expected. In K&R C it is the same but strictly
> checking in C++ they are different things.


So I was wondering which compiler was right: g++ or clang++?

Mojca


More information about the macports-dev mailing list