覆盖#define值 [英] override #define value
本文介绍了覆盖#define值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如标题所述,我们可以覆盖#define的值
喜欢
Hi,
as title said, can we override #define's value
like
#include<stdio.h>
#define LIM 5
// in main function
// scanf x's value and assign it to LIM
// LIM = x;
我们能做到吗?
can we do that ??
推荐答案
你做不到。
#define在编译器的预编译阶段被替换(文本)。
You cannot do that.
The #define are replaced (textually) in by the pre-compilation phase of the compiler.
不,你不能用v覆盖#define常量在运行时可以运行。原因很简单:#define语句由编译器处理 - 在编译时,即在程序运行之前很久。并且编译器将这些值作为常量插入到程序代码中。
但是你可以执行以下操作:
No, you cannot override a #define constant with variable at run-time. The reason is simple: #define statements are processed by the compiler -- at compile-time, i.e. long before your program runs. And the compiler inserts those values as constants in your program code.
But you can do the following:
#define LIM 5
void MyFunction ()
{
int x;
if (!scanf ("%d", &x) != 1)
x = LIM;
...
}
正如其他解决方案所示,您无法在运行时更改值,但您可以在编译过程中更改宏的编译时定义。例如:
As the other solutions have indicated, you can't change a value at runtime, but you can change the compile time definition of a macro during the compile process. For example:
void foo()
{
#define LIM 5
int zork[LIM]; // defined as size 5
#undef LIM
#define LIM 42
int blork[LIM]; // defined as size 42
#undef LIM
#define LIM 123
// At this point, LIM is 123, but zork is still size 5 and blork is still
// size 42. This does not change during the compile process or during runtime.
#undef LIM
// At this point, LIM is undefined.
}
这篇关于覆盖#define值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文