gpt4 book ai didi

C - 初始值设定项不是字符串常量

转载 作者:太空狗 更新时间:2023-10-29 17:21:06 25 4
gpt4 key购买 nike

我知道 c 文件范围内初始化器的限制:你不能使用变量(甚至是 const)、函数等......但我真的不明白为什么这不起作用:

#include <stdlib.h>
#include <stdio.h>

//unsigned long a = "string"[0] > '0'; // this does not compile
unsigned long a = 's' > '0'; // this works fine, output is "a = 1"

int main(void)
{
printf("a = %lu\n",a);

return 0;
}

为什么带有字符串文字的行给出:错误:初始化元素不是常量。字符串文字不被认为是常量吗?有什么办法让它发挥作用吗?

提前致谢

最佳答案

根据 N1570 (C11) §6.7.9/p4,您的变量具有静态存储持续时间:

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

字符串文字具有静态存储持续时间 §6.4.5/p6 ,所以它们的地址可以被认为是常量表达式(这就是它们被允许作为初始值设定项的原因)。但是你正试图访问这样一个地址的值,而 C 标准明确禁止它。引用§6.6/p9 ,强调我的:

An address constant is a null pointer, a pointer to an lvalue designating an object of static storage duration, or a pointer to a function designator; it shall be created explicitly using the unary & operator or an integer constant cast to pointer type, or implicitly by the use of an expression of array or function type. The array-subscript [] and member-access . and -> operators, the address & and indirection * unary operators, and pointer casts may be used in the creation of an address constant, but the value of an object shall not be accessed by use of these operators.

另一方面,当您使用字符常量 进行比较时,您会获得一个有效的常量表达式。

关于C - 初始值设定项不是字符串常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48562546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com