-1

The following code:

  const char * p;
  char * i = p;

does not compile in CPP.

error: invalid conversion from 'const char*' to 'char*

However, there are no compilation errors when compiling as C code. Why does C allow implicit casting of a const pointer to a non const pointer?

Poogy
  • 2,597
  • 7
  • 20
  • 35
  • C and C++ are two very different languages with their own rules and semantics (despite a somewhat similar syntax). Const-correctness is one area where they differ. – Some programmer dude Jun 24 '20 at 11:20
  • MSVC complains: *warning C4090: 'initializing': different 'const' qualifiers* – Weather Vane Jun 24 '20 at 11:22
  • They are indeed different. But this behavior renders the const keyword useless in this scenario... – Poogy Jun 24 '20 at 11:22
  • 1
    Your C compiler didn't give you a warning? MSVC and `gcc` both issue warnings. – lurker Jun 24 '20 at 11:22
  • 2
    How did you compile? C has a long and rich history. Some compilers aren't strict by default, because that would break old code. You may need to tell it explicitly. In a GCC like compilers that would be with a `-pedantic` flag. – StoryTeller - Unslander Monica Jun 24 '20 at 11:23
  • Yes, I see a warning but not an error like I would expect. My question is why is there no error? – Poogy Jun 24 '20 at 11:27
  • 2
    @DM - It's still standard conforming. The standard doesn't say that a constraint violation must result in compilation terminating. All it says is that the compiler must issue a diagnostic. A warning is a diagnostic. An implementation is free to continue translating the program, as though it offered an extension. If you prefer not to do that, you can use something like the `-pedantic-errors` flag. – StoryTeller - Unslander Monica Jun 24 '20 at 11:30
  • @Someprogrammerdude Although there are some minor differences, this code is illegal in both languages – M.M Jun 24 '20 at 12:45

1 Answers1

0

C has a concept of the Undefined Behaviour. It allows it to compile programs even if compiler is noticing the possibility of the UB. In many cases warning is omitted.

In this case (gcc)

warning: initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]

https://godbolt.org/z/Q8CHgU

0___________
  • 60,014
  • 4
  • 34
  • 74