简体   繁体   中英

Why converting Foo** → const Foo** is an error in C++, but only a warning in C?

char const c = 'x';       /* 1 */
char *p1;                 /* 2 */
char const **p2 = &p1;    /* 3 */
*p2 = &c;                 /* 4 */
*p1 = 'X';                /* 5 */

Line 3 is disallowed in C and is invalid in C++. However, one gets an error in C++, but only a warning in C. The question is - why only a warning?

Both C & C++ deal with statement 3 as that "Assigning const char** with char** discards the const qualifier" The difference is; C++ is more strict than C and doesn't allow const qualifier discarding. This is really convenient in C++ and does lead to no issues contrary to C.

Imagine the following code:

    char const c = 'x';
    char *p1 = &c;
    *p1 = 'A';

    printf("c address: 0x%X, p1 is pointing to: 0x%X\n", &c, p1);
    printf("%c\n", c);
    printf("%c\n", *p1);

This is a compilable C code. One would think that assigning a new value to *p1 should not be possible as it points to a const variable. Also one would think that if it did happen and we could change the value of what p is pointing at this will also change the value of c But this is not the case!!

The above code surprisingly generates:

c address: 0xEF3E146B, p1 is pointing to: 0xEF3E146B
x
A

So allowing this const qualifier to be discarded does lead to undefined behavior (which means it's up to the compiler to decide what to do). This is fixed in C++ to avoid such ambiguities.

C has much more relaxed pointer rules than C++. C++ enforces a lot more type safety than C. Some of this is up to compilers to decide only to warn in C.

One example to look at is malloc, where char* str = malloc(50); is perfectly fine C but must be char* str = (char*) malloc(50); in C++.

The short answer is: because they are different languages and have different rules. There is no C/C++ language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM