gpt4 book ai didi

c - 测试#define CONSTANT

转载 作者:太空宇宙 更新时间:2023-11-04 08:23:40 26 4
gpt4 key购买 nike

我不是程序员,但我需要去做! :) 我的问题是我需要定义一些常量来设置或不设置我的代码的某些特定部分,使用#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 block ,而是使用了 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 都被定义了,不仅仅是被选中的那个,它将是BA、B 和 C 定义了在同一组变量中工作的部分代码。我需要根据 isample 设置其中之一。

最佳答案

您正在使用错误的方法接近它。 isample 的值是在运行时确定的,而不是编译时。

当你使用

#define SAMPLE isample

编译器在所有将 SAMPLE 视为标记的地方,都会用 isample 替换该标记。那不是你想要的。您希望编译器将所有 SAMPLE 替换为 isample 的值。

您需要使用编译器标志设置SAMPLE 的值。使用 gcc,您可以使用:

gcc -DSAMPLE=1 ...

并删除该行

#define SAMPLE isample

关于c - 测试#define CONSTANT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32127477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com