Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the C compiler (clang) enforce const?

Tags:

c

constants

With Clang, the following :

#include <stdio.h>

int main(void)
{   double const x = 1.234;
    double *p = (double *) &x;
    /* Same with double *p = &x; but with a mere warning from clang
       Clang++ does raise an error in this case.
    */
    *p = 5.678;

    printf("*p = %f\n", *p);
    printf(" x = %f\n", x);

    if (&x == p) {
        printf("&x = %p\n", &x);
        printf(" p = %p\n", p);
    }

    return 0;
}

gives the output:

*p = 5.678000
x = 1.234000
&x = 00000080288FFEA8
p = 00000080288FFEA8

How exactly does the compiler do this? How can the compiler successfully compile and avoid, say, the following output:

*p = 5.678000
x = 5.678000
&x = 00000080288FFEA8
p = 00000080288FFEA8

like image 268
Amaterasu Avatar asked Dec 08 '22 11:12

Amaterasu


1 Answers

The behaviour on modifying an object which was originally const via a cast which removes that const is undefined.

Whether or not a compiler warns you about undefined behavior is up to the compiler. To do so in full generality is impossible.

Optimising compilers will make assumptions based on the fact that your program does not contain undefined behaviour. The Clang output is consistent with it substituting 1.234 for x in that printf call; that's legitimate since x is not allowed to change.

like image 182
Bathsheba Avatar answered Dec 09 '22 23:12

Bathsheba