-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?

8
  • 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. Commented Jun 24, 2020 at 11:20
  • MSVC complains: warning C4090: 'initializing': different 'const' qualifiers Commented Jun 24, 2020 at 11:22
  • 1
    Your C compiler didn't give you a warning? MSVC and gcc both issue warnings. Commented Jun 24, 2020 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. Commented Jun 24, 2020 at 11:23
  • 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. Commented Jun 24, 2020 at 11:30

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.