0

我正在研究 C 中的只读复合文字。当我尝试在取消引用运算符的帮助下更改其值时,值发生了变化!我现在很困惑为什么会这样。

此外,当我编译并运行程序(不尝试更改其值)时,它显示此错误:

Code_Testing.c:5:14: warning: initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
    5 |     int *r = (const int[3]){6, 14, -98}; // Read Only compound Literal
      |

我不明白为什么它忽略了const限定符。

我知道const限定符会丢弃任何更改,但这里复合文字的值发生了变化!

你能解释一下我在哪里犯了错误吗?

我写的程序是这样的:

#include <stdio.h>

int main(void)
{
    int *r = (const int[3]){6, 14, -98}; // Read Only compound Literal
    *r += 99;
    printf("The changed value is = %d", *r);
    return 0;
}

输出是:

Code_Testing.c:5:14: warning: initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
    5 |     int *r = (const int[3]){6, 14, -98}; // Read Only compound Literal
      |              ^
The changed value is = 105
4

2 回答 2

2

您将const int[]数组分配给指向非const值的指针。这意味着作为程序员明确丢弃const限定符。(const右侧的实际上确实将文字声明为const。)

编译器会就此向您发出警告。

要修复警告,您必须使用

const int *r = (const int[3]){6, 14, -98}; // Read Only compound Literal

然后你会在该行得到一个错误

*r += 99;

您要修改值的位置。

const限定符不会“放弃任何更改” 。如您所见,有一些方法可以修改该值。(但这是未定义的行为。)限定符告诉编译器不应修改该值,并且当您的代码修改它或检测到可能导致修改值的使用时,编译器将显示错误或
警告类型。constconst

于 2020-12-29T14:30:54.663 回答
0

如果您尝试使用非 const 限定类型的左值修改 const 限定对象的值,则它是未定义的行为

引用C11,第 6.7.3 章

如果尝试通过使用具有非 const 限定类型的左值来修改使用 const 限定类型定义的对象,则行为未定义。[...]

此处的赋值丢弃了初始化程序中的 const 限定符,并将其分配给非 const 限定的左值,因此您的编译器试图警告您潜在的陷阱。

于 2020-12-29T14:25:34.520 回答