Tag: const

关于使用指针修改const变量的困惑

以下示例在我的理解中增加了混淆。 我无法理解如何修改const变量local。 请帮我理解一下。 /* Compile code without optimization option */ // volatile.c #include int main(void) { const int local = 10; int *ptr = (int*) &local; printf(“Initial value of local : %d \n”, local); *ptr = 100; printf(“Modified value of local: %d \n”, local); return 0; } $ gcc volatile.c -o volatile -save-temps $ ./volatile […]

Const变量在C中用指针改变

变量i被声明为const,但我仍然可以使用指向它的内存位置的指针来更改该值。 这怎么可能? int main() { const int i = 11; int *ip = &i; *ip=100; printf(“%d\n”,*ip); printf(“%d\n”,i); } 当我编译时,我得到这个警告: test.c: In function ‘main’: test.c:11: warning: initialization discards qualifiers from pointer target type 输出就是这个 100 100

C – 通过const声明访问非const

是通过C标准允许的const声明访问非const对象吗? 例如,以下代码保证在符合标准的平台上编译和输出23和42? 翻译单位A: int a = 23; void foo(void) { a = 42; } 翻译单位B: #include extern volatile const int a; void foo(void); int main(void) { printf(“%i\n”, a); foo(); printf(“%i\n”, a); return 0; } 在ISO / IEC 9899:1999中,我刚刚发现(6.7.3,第5段): 如果尝试通过使用具有非const限定类型的左值来修改使用const限定类型定义的对象,则行为未定义。 但在上面的例子中,对象没有定义为const (只是声明)。 UPDATE 我终于在ISO / IEC 9899:1999中找到了它。 6.2.7,2 引用同一对象或函数的所有声明都应具有兼容类型; 否则,行为未定义。 6.7.3,9 要使两种合格类型兼容,两者都应具有相同类型的兼容类型; […] 所以,它是未定义的行为。

GNU C中的__attribute __((const))vs __attribute __((pure))

GNU C中__attribute__((const))和__attribute__((pure))什么区别? __attribute__((const)) int f() { /* … */ return 4; } VS __attribute__((pure)) int f() { /* … */ return 4; }

C语言中限定词的深层分析

const变量在哪里准确存储,它的行为如何变化? 比如说: const int i=10; // stores where ? main() { const int j=20; //stores where? return 0; } 如果答案是代码段,那么以下代码如何工作? main() { const int j=20; int *p; p=&j; (*p)++; return 0 ; } 这段代码工作正常……如何更改只读内存? 它是如何存储的? 请详细解释一下。

C函数const多维数组参数中的奇怪警告

我对这段代码有一些奇怪的警告: typedef double mat4[4][4]; void mprod4(mat4 r, const mat4 a, const mat4 b) { /* yes, function is empty */ } int main() { mat4 mr, ma, mb; mprod4(mr, ma, mb); } gcc输出如下: $ gcc -o test test.c test.c: In function ‘main’: test.c:13: warning: passing argument 2 of ‘mprod4’ from incompatible pointer type test.c:4: note: […]

使用C中的指针的const用法

我正在讨论C并且有一个关于使用指针的const用法的问题。 我理解以下代码: const char *someArray 这是定义指向char类型的指针, const修饰符意味着不能更改someArray存储的值。 但是,以下是什么意思? char * const array 这是指定参数的另一种方法,该参数是指向名为“array”的数组的char指针,该数组是const且无法修改? 最后,这个组合意味着什么: const char * const s2 作为参考,这些来自第7章中的Deitel C编程书,所有这些都被用作传递给函数的参数。

我们可以通过指针改变用const定义的对象的值吗?

#include int main() { const int a = 12; int *p; p = &a; *p = 70; } 它会起作用吗?