2

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;
}
21
  • 2
    If you do so, its Undefined behaviour. Commented Aug 24, 2013 at 8:57
  • 1
    ur compiler shouldn't allow that, not allowed to convert from const int* to int* const: ideone.com/AnuWLM Commented Aug 24, 2013 at 8:57
  • 2
    Removed C++ tag: this will not compile as C++. A C compiler will probably emit a scary warning. Commented Aug 24, 2013 at 8:58
  • 5
    int main()... Commented Aug 24, 2013 at 8:58
  • 1
    @Krishna did gcc not worn about the bad pointer assingment p=&x? Commented Aug 24, 2013 at 9:01

2 Answers 2

9

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.

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

1 Comment

Standard quotation == automatic +1.
3
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.