Undefined behaviour of const

前端 未结 4 764
灰色年华
灰色年华 2020-12-10 09:42

I never thought I will be going to ask this question but I have no idea why this happens.

const int a = 3; 
int *ptr;
ptr = (int*)( &a );
printf( \"A=%d\         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 10:10

    In fact your program invokes undefined behavior because of two reasons:
    1.You are printing an address with wrong specifier %d. Correct specifier for that is %p.
    2.You are modifying a variable with const specifier.

    If the behavior is undefined then anything could happen. You may get either expected or unexpected result.
    Standard says about it;

    3.4.3 undefined behavior

    behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

提交回复
热议问题