25:警告:初始化元素不是常量表达式 [英] 25: warning: initializer element is not a constant expression

查看:17
本文介绍了25:警告:初始化元素不是常量表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC 在尝试编译时给我以下警告消息:

GCC gives me the following warning message when trying to compile:

las.c:13:18: warning: initializer element is not a constant expression [enabled by default]
 const int ROWS = pow (2, MESH_K);

与此相关的代码部分是:

The relevant code portions for this is:

 #define MESH_K 10
 #define BUFF_SIZE 30

 const int ROWS = pow (2, MESH_K);

我需要在后面的代码中同时使用 MESH_K 和 ROWS.我知道函数调用可能导致 GCC 相信这不是一个常量表达式.但是,鉴于对 pow 的调用本质上是一个常量,是否有更好的方法来实现它(也许是预处理器宏?)并消除警告?

I need to use both MESH_K and ROWS at later points in the code. I understand that function calls are probably leading GCC to believe that this is not a constant expression. However given that this call to pow is essentially a constant, is there a better way to implement it (pre-processor macros perhaps?) and eliminate the warning?

我不介意在这部分代码中为了性能而牺牲可读性,因此欢迎任何和所有复杂的解决方案.

I don't mind sacrificing readability for performance in this part of the code, so any and all complex solutions are welcome.

推荐答案

我相信你的答案是 这里.

这将在 C++ 中正常编译,但在 C 中则不行.

This will compile fine in C++, but not in C.

这与C语言有关.在 C 语言中使用静态对象存储持续时间必须用常量表达式或使用包含常量表达式的聚合初始值设定项.

It has to do with C language. In C language objects with static storage duration has to be initialized with constant expressions or with aggregate initializers containing constant expressions.

大"对象在 C 中永远不是常量表达式,即使对象被声明为 const.

A "large" object is never a constant expression in C, even if the object is declared as const.

此外,在 C 语言中,术语常量"指的是字面量常量(如 1、'a'、0xFF 等)和枚举成员.const 限定的对象(任何类型)在 C 语言中不是常量术语.它们不能用于对象的初始化器静态存储持续时间,无论其类型如何.

Moreover, in C language the term "constant" refers to literal constants (like 1, 'a', 0xFF and so on) and enum members. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.

就像 squeamish 所说,const int ROWS = 1 << 可以,但是:

Like squeamish says, const int ROWS = 1 << MESH_K; will work, but:

int test = 10;

const int ROWS = 1 << test;

不会工作.我的猜测是 MESH_K 作为文字粘贴到代码中,因此解析为 C 常量.

Will NOT work. My guess is that MESH_K is pasted into the code as a literal, and therefore resolves to a C constant.

这篇关于25:警告:初始化元素不是常量表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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