为什么我没有得到下面的C程序预期的输出? [英] Why i am not getting the expected output in the following c programme?

查看:172
本文介绍了为什么我没有得到下面的C程序预期的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  什么“ STR的#define(一)#一”的怎么办?结果
  在C语言编程宏评价


 的#include<&stdio.h中GT;
的#define F(A,B)一个## b
的#define克(一)#a的
的#define小时(一)克(一)诠释的main()
{
      的printf(%S \\ n,H(F(1,2)));
      的printf(%S \\ N,G(F(1,2)));
      返回0;
 }

我期待的输出是相同的两个与printf。但我得到不同(如下)

  12
F(1,2)

可以有人解释是什么原因,为什么它具体发生了什么?


解决方案

我一个额外的延长线程序

 的printf(%d个\\ N,F(1,2));

这反过来,结果到

 的printf(%d个\\ N,12);

(调用的gcc -E )。

您两条线导致成

 的printf(%S \\ n,12);
的printf(%S \\ n,F(1,2));

在这里会发生什么事?

F(1,2)是明确的 - 1 2 先手粘在一起。

克(东西)只是再现的东西作为一个字符串,没有特殊对待它 - > F(1,2)

H(东西)反过来,让结果克(东西)扩大。

Possible Duplicate:
What does “#define STR(a) #a” do?
Macros evaluation in c programming language

#include <stdio.h>
#define f(a,b) a##b
#define g(a)   #a
#define h(a) g(a)

int main()
{
      printf("%s\n",h(f(1,2)));
      printf("%s\n",g(f(1,2)));
      return 0;
 }

I was expecting the output to be same for both the printf. But what I am getting is different(given below)

12
f(1,2)

can someone explain what is the reason and why is it happening in detail?

解决方案

I extended your program with an additional line

printf("%d\n",f(1,2));

which, in turn, results into

printf("%d\n",12);

(called with gcc -E).

Your two lines result into

printf("%s\n","12");
printf("%s\n","f(1,2)");

What happens here?

f(1,2) is clear - 1 and 2 just get sticked together.

g(something) just reproduces something as a string, without treating it specially -> "f(1,2)".

h(something), in turn, lets the result of g(something) expand.

这篇关于为什么我没有得到下面的C程序预期的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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