在C中,当尝试##时,如果将int作为变量提供,则它会很奇怪。 [英] In C, when trying ##, it works weird if int are provided as variables.

查看:62
本文介绍了在C中,当尝试##时,如果将int作为变量提供,则它会很奇怪。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这个功能:

#include< stdio.h>

#define UNI(x,y)x ## 2

int main(void){

int i = 5;

int i2 = -2;

printf(%d,UNI(i,i2));

返回0;

}

这打印-2,应该打印52!



我有什么试过:



#define仅在##之后的数字为2时才有效。所有其他数字都会导致编译错误。此外,如果数字为2,则无论i的值如何,结果为-2。

认为x ## 2将始终转为y结果。为什么?

解决方案

对我来说,我正确地收到一条错误消息:

 main.c:14 :18:错误:'i2'未声明(在此函数中首次使用)



我怀疑您还遇到了编译错误,而您正在执行的EXE文件来自上次成功编译。



#define 是一个 预处理器指令 ,它将源文件中的文本替换为传递给实际编译器之前的文本。

UNI(i)将被替换与 i2 不是变量的内容,即后跟2,因为预处理器部分在编译之前就已完成,并且不能引用运行时值。


There is this function:
#include <stdio.h>
#define UNI(x,y) x##2
int main(void) {
int i = 5;
int i2 = -2;
printf("%d",UNI(i,i2));
return 0;
}
This prints -2, when it should print 52!

What I have tried:

The #define only works if the number after ## is 2. All other numbers result in an error of compilation. Also, if the number is 2, the result is -2 regardless of the value of i.
Figured that x##2 will always turn the y result. Why?

解决方案

For me, I rightly get an error message:

main.c:14:18: error: ‘i2’ undeclared (first use in this function)


I suspect that you also got a compilation error and the EXE file you are executing is from the last successful compilation.

#define is a preprocessor directive, and it replaces text in your source file before before it is passed to the actual compiler.
UNI(i) will be replaced with i2 not "the content of the variable ie followed by a "2" as the preprocessor part is completed well before compilation, and can't reference run time values.


这篇关于在C中,当尝试##时,如果将int作为变量提供,则它会很奇怪。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆