【发布时间】:2015-08-20 20:11:53
【问题描述】:
我不是程序员,但我需要去做! :) 我的问题是我需要定义一些常量来设置或不设置我的代码的某些特定部分,并且使用#define 比使用普通变量更好。代码如下。根据之前进行的字符串之间的比较,isample 可以等于 0、1、2 或 3。假设 isample = 1,那么代码打印出常量 SAMPLE 等于 1,但随后它进入 if isample == 0 !!!定义有问题。怎么了?还有其他方法吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int isample = 1;
#define SAMPLE isample
printf("\nSAMPLE %d", SAMPLE);
#if SAMPLE == 0
#define A
#define AA
printf("\nA");
#elif SAMPLE == 1
#define B
printf("\nB");
#elif SAMPLE == 2
#define C
printf("\nC");
#else
printf("\nOTHER");
#endif
printf("\nBye");
}
结果:
SAMPLE 1
A
Bye
我也试过了:
#define SAMPLE 4
#undef SAMPLE
#define SAMPLE isample
结果是一样的。
我也尝试过使用变量。我没有使用#if 块,而是使用if:
if (SAMPLE == 0)
{
#define A
#define AA
printf("\nA");
}
else if (SAMPLE == 1)
{
#define B
printf("\nB");
}
else if (SAMPLE == 2)
{
#define C
printf("\nC");
}
else
{
printf("\nOTHER");
}
int abc, def;
#ifdef A
abc = 1;
def = 2;
#endif
#ifdef B
abc = 3;
def = 4;
#endif
#ifdef C
abc = 5;
def = 6;
#endif
printf("\nabc %d, def %d\n", abc, def);
结果:
SAMPLE 1
B
abc 5, def 6
所以所有#define 都被定义了,不仅是选定的B。 A, B and C 定义在同一组变量中工作的部分代码。我需要根据isample设置其中之一。
【问题讨论】:
-
宏是在程序编译时处理的,而不是在程序运行时处理的。他们不能访问普通的变量值。
-
@JensGustedt
A和AA已定义,B和C未定义。为了在#if中进行表达式评估,未定义的标记被替换为0 -
所以要做我想做的事,我有两个选择:1)每次运行代码时“手动”定义
SAMPLE; 2)使用普通变量,去掉我定义的所有CONSTANT。我正在做选项 1,但我已经遇到了一些问题,当我忘记更改它时,并且由于代码需要很长时间才能运行,最好确保它会做正确的事情。我想我会选择选项 2 并重写代码...
标签: c constants c-preprocessor