您可以在 if 语句中使用 #define 值(在 C 程序中)吗?
我是 C 编程新手。我认为当您输入类似 #define Const 5000
的内容时,编译器只会在编译时将每个 Const 实例替换为 5000。这是错误的吗? 我尝试在我的代码中执行此操作,但出现语法错误。为什么我不能这样做?
#define STEPS_PER_REV 12345
... in some function
if(CurrentPosition >= STEPS_PER_REV)
{
// do some stuff here
}
编译器抱怨 if 语句存在语法错误,但没有提供任何详细信息。
I am new at C programming. I thought when you type something like #define Const 5000
that the compiler just replaces every instance of Const with 5000 at compile time. Is that wrong?
I try doing this in my code and I get a syntax error. Why can't i do this?
#define STEPS_PER_REV 12345
... in some function
if(CurrentPosition >= STEPS_PER_REV)
{
// do some stuff here
}
The compiler complains about the if statement with a syntax error that gives me no details.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
评论中的人是对的。几乎可以肯定,#define 末尾有一个分号。这意味着你的赋值变成:(
假设你在行尾有一个分号...)
但是你的 if 变成:
这当然是无效的。
请记住,#defines 不是 C 代码。他们不需要分号。
the people in the comments are right. You almost definitely have a semicolon at the end of your #define. This means that your assignment becomes:
(assuming that you HAD a semicolon at the end of the line...)
but your if becomes:
which is of course invalid.
remember, #defines are NOT C code. They don't need semicolons.
您的代码片段是正确的。 #define 实际上是一个字符串替换(具有更多的智能)。
您可以使用 -E 选项检查预处理器在 gcc 中执行的操作,该选项将在预处理器运行后输出代码。
Your code fragment is correct. #define is literally a string subsitution (with a bit more intelligence).
You can check what the preprocessor is doing in gcc by using the -E option, which will output the code after the pre-processor has run.
您是正确的,C 预处理器只会将
STEPS_PER_REV
替换为12345
。因此,根据您提供的代码,您的 if 语句看起来不错。为了弄清楚这一点,您能否发布您的代码和错误消息的实际内容。
You are correct in that the C preprocessor will just replace
STEPS_PER_REV
with12345
. So your if statement looks fine, based on the code you provided.To get to the bottom of this, could you please post your code and the actual contents of the error message.
当您说编译器用宏的内容替换每个实例时,您是对的。检查CurrentPosition的类型,可能是错误所在。
You are right when you say that the compiler replaces every instance with the content of the macro. Check the type of CurrentPosition, probably the error is there.
是的,但这应该是一个常量,而不是宏。您可能在比较中得到了错误的类型。
Yes, but that should be a const, not a macro. You probably getting the wrong type in your comparison.
c 中的 #define 是宏,c 预处理器使用它们来替换它们。例如,在源代码中的
后预处理步骤中。这样它们就可以用在 if 语句的布尔语句中。
#define in c are macros, they are used by c preprocessor to replace them when they're found. For example in your source code the
after preprocessing step. So that they could be used in boolean statetments in if sentences.