c++cdefine-syntax

How to handle C char* defines in C++


I am porting some C code to C++ right now. The C code is using multiple defines like:

#define IPADDRESS "fd9e:21a7:a92c:2323::1"

The problem that i have is that when i am calling C functions with the defines that are now in the C++ file i get:

warning: ISO C++ forbids converting a string constant to ‘char*’

I don't want to modify the C functions in this case and since I am still new to C++ and i was wondering how to handle this problem. I guess it isn't possible to tell C++ to handle these defines as a char* and not as a string constant so i was wondering if it is safe to cast the string constant to a char* in this case or if there is a function that i should use for this?

I appreciate your help!


Solution

  • The problem is that string literals "this is a string literal" are of type char[] in C but const char[] in C++. So if you have sloppily written C code which doesn't use const correctness of function parameters, that code will break when ported to C++. Because you can't pass a const char* to a function expecting char*.

    And no, it is generally not safe to "cast away" const - doing so is undefined behavior in C and C++ both.

    The solution is to fix the original C code. Not using const correctness is incorrect design, both in C and C++. If the C++ compiler supports compound literals, then one possible fix could also be:

    #define IPADDRESS (char[]){"fd9e:21a7:a92c:2323::1"}