1

I am converting a large code base form C to C++. I got a compiler error for the following line of code:

char SingleDigit[2] = {" \n"};

error: a value of type "const char [3]" cannot be used to initialize an entity of type "char [2]"

" \n" has just one whitespace.

Has the initialization of a char array changed for C to C++? Is " " (with one space) actually a char array of length to (null termination).

Was this a bug in C already?

I use the Intel compiler version 19.1.1.216 and Windows 10 for the C and the C++ code.

phuclv
  • 37,963
  • 15
  • 156
  • 475
schorsch312
  • 5,553
  • 5
  • 28
  • 57
  • 1
    In C the 0-terminator does not have to fit into the array, but in C++ it must. It is probably a bug in C, but a constraint violation in C++. – mch May 10 '21 at 06:47
  • I tested it with `print("%d",'\n')` and I receive `10` as result. So possibly that compile assume the zero termination in `" \n"` as `" \n\0"` – Silver May 10 '21 at 06:48
  • See [How should character arrays be used as strings?](https://stackoverflow.com/questions/58526131/how-should-character-arrays-be-used-as-strings) – Lundin May 10 '21 at 09:38

0 Answers0