我不是程序员,但我需要这样做! :)我的问题是我需要定义一些常量来设置或不设置我的代码的某些特定部分,并且最好使用#define而不是正常变量。代码是波纹管。根据之前所做的字符串比较,isample可以等于0,1,2或3。假设isample = 1,那么代码输出常量SAMPLE等于1,但是它会进入if isample == 0!定义有问题。发生什么事?还有另一种方法可以做到吗?testing #define CONSTANT
#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
设置其中之一。
宏的处理。他们不能访问普通的变量值。 – Barmar
@JensGustedt定义了'A'和'AA','B'和'C'不是。未定义的标记被'0'替换为'#if'中的表达式评估目的 –
所以要做我想做的事情,我有两个选择: 1)每次定义“SAMPLE”时,我运行代码; 2)使用正常变量,并取消所有我定义的“常量”。 我正在做选项1,但是我已经遇到了一些问题,当我忘记更改它时,并且由于代码需要很长时间才能运行,最好确保它能做正确的事情。我想我会选择选项2并重写代码... – Thaise