【发布时间】:2013-05-26 20:12:43
【问题描述】:
我找到了很多关于 C#、java 中数据类型可变性的信息……但是纯 C 呢?
例如,int 在 C 中是否默认不可变?
例如看下面的代码示例:
#include <stdio.h>
int main()
{
int a,b,c;
b=0;
c=0;
a=b+c;
b=1;
c=2;
printf("1st time %d\n",a);//gives out 0
c=3;
printf("2nd time %d",a);//gives out 0
return 0;
}
上面的代码表明一个普通的int是不可变的,对吗?
【问题讨论】:
-
只有声明为 const 的数据是不可变的
-
Roger 在某种意义上是正确的,但它甚至可以覆盖
const int的内存位置。 -
@Shredderroy 不一定,这取决于
const int的范围和系统。在具有真正只读存储器的嵌入式系统中,const变量将存储在闪存/EEPROM 中。那么无论你做了多少丑陋的演员,你都不能覆盖它们。但另一方面,只有文件范围(全局/静态)常量变量被放置在真正的只读内存中,因为在嵌入式系统上,您可能也需要不可变特性。因此,总是可以覆盖局部 const 变量,因为它们总是存储在 RAM 中。 -
@Shredderroy 我相当有信心尝试覆盖
const任何东西都是 C 中的 UB(未定义行为)。我需要查找它 - 已经晚了。写可能/可能不工作。示例:const数据存储器在程序加载后变为只读。您可以尝试覆盖,但没有任何变化。 -
@chux 是的,它始终是未定义的行为。 C11 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."