Visual Studio 中 const 与 #define 的问题 [英] Problem with const vs #define in Visual Studio

查看:27
本文介绍了Visual Studio 中 const 与 #define 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,#define xyconst int x = y; 应该在 Visual Studio 编译器下工作相同,但 const int x = y; 是首选方法.

From what I understand, #define x y and const int x = y; should work identically under the Visual Studio compiler, but const int x = y; is the preferred method.

我的 C 代码看起来像这样:

The C code I have looks something like this:

static const int x = 100000;

void SomeFunction(...)
{
    volatile static int y = x;
    ...
}

这里的问题在于 y 的声明.如果我对 x 使用 #define,则没有问题,但是使用上述代码会导致编译器返回错误 c2099:初始化程序不是常量."

The problem here is with the declaration of y. If I use a #define for x, then there are no problems, but using the above code results in the compiler returning with "error c2099: initializer is not a constant."

我正在尝试从命令行进行编译,并且我没有使用任何编译器标志,所以我不确定是否需要设置一个标志以便编译器优化 const - 或者如果我偶然发现了某种特殊情况.

I'm trying to compile from the command line, and I'm not using any compiler flags, so I'm not sure if I need to set a flag in order for the compiler to optimize out the const - or if I stumbled onto some kind of special case.

将程序编译为 C++ 程序也可以,但如果可能的话,我宁愿避免这种情况.

Compiling the program as a C++ program also works, but I would rather avoid that, if possible.

推荐答案

我完全不了解 C 标准,但我之前已经阅读过相关内容.这是我的理解.

I don't know the C standard inside out but I've read about this before. Here's my understanding.

严格的 ANSI C 编译器只允许您使用常量表达式作为初始化器.请注意,常量表达式只能包含字面值,不能包含常量限定的变量.

A strict ANSI C compiler will only allow you to use constant expressions as initialisers. Note that a constant expression can only involve literal values, not variables that are const-qualified.

我相信这是因为在编译期间,编译器必须计算要初始化的值,以便它可以将该值静态推入堆栈,而无需在运行时进行任何计算.甚至 const 限定的变量也可以更改(通过删除 const 限定符并更改值).

I believe this is because during compilation, the compiler must compute the value to initialise so that it can statically push this value onto the stack without any computation required at runtime. Even const-qualified variables can change (by removing the const-qualifier and changing the value).

const int x = 5;
*(int *)&x = 3;

我认为 C99 允许您仅在函数范围内使用 const 限定的变量进行初始化,文件范围的变量仍受相同限制的约束.

I think C99 allows you to initialise with const-qualified variables at function scope only, file-scope variables are still bound by the same restriction.

这篇关于Visual Studio 中 const 与 #define 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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