Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const variable value is changed by using a pointer

Tags:

c

The output of the following program is 50 on gcc. How is it possible as x is constant variable and *p is x itself as p is a constant pointer pointing to value at x. Where as turbo c gives compiler error. Is it an undefined behaviour? please explain.

#include<stdio.h>

int main()
{
    const int x = 25;
    int * const p = &x;
    *p = 2 * x;
    printf("%d", x);
    return 0;
}
like image 669
Krishna Kittu Avatar asked Jun 18 '26 15:06

Krishna Kittu


2 Answers

It is possible to change it but the behavior is undefined, as its mentioned in the standard!

Its in c11 under 6.7.3

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

like image 56
dhein Avatar answered Jun 20 '26 05:06

dhein


int * const p=&x;

This is not a valid program. &x is of type const int * but you are assigning the pointer value to an object of type int * const: the compiler has to issue a warning and is allowed to stop compilation.

like image 20
ouah Avatar answered Jun 20 '26 06:06

ouah