常量变量值是通过使用一指针改变 [英] const variable value is changed by using a pointer

查看:173
本文介绍了常量变量值是通过使用一指针改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序的输出是50上的gcc。
这怎么可能为x是恒定的变量,* p是X本身作为p是一个常量指针在x指向值。
作为在哪里的Turbo C会产生编译错误。
它是一个未定义的行为?请解释一下。

 #包括LT&;&stdio.h中GT;诠释的main()
{
    const int的X = 25;
    INT * const的P =&放大器; X;
    * P = 2 * X;
    的printf(%D,X);
    返回0;
}


解决方案

有可能改变它,但行为是不确定的,因为它在标准中!

及其C11 6.7.3在


  

如果试图修改通过使用非const限定型左值的const限定的类型定义的对象,其行为是不确定的。如果试图指通过使用具有非易失性限定类型的左值的volatile限定类型定义的对象,行为是不确定的。


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;
}

解决方案

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.

这篇关于常量变量值是通过使用一指针改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆