此预处理器指令C / C ++需要说明 [英] Explanation needed for this pre-processor directive C/C++

查看:147
本文介绍了此预处理器指令C / C ++需要说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一些测试中解决这个问题,但后来当我在家里运行它,它给出了意想不到的答案。
我无法理解此代码:

I tried to solve this problem in some test, but later when i ran it at home, it gave unexpected answer. I am not able to understand this code:

#include <stdio.h>
#include <conio.h>
#define swap(a,b) temp=a; a=b; b=temp;
int main()
{
int i, j, temp;
i=5;
j=10;
temp=0;
if( i > j) //evaluates to false
swap( i, j );
printf( "%d %d %d", i, j, temp); //expected output: 5 10 0
getch();
return 0;
}

输出我得到的是:10 0 0

Output i am getting is: 10 0 0

请有人解释它是如何工作的。

Please someone explain how is it working.

推荐答案

b

if( i > j) //evaluates to false
swap( i, j );

成为

if( i > j) //evaluates to false
temp=i; i=j; j=temp;

相当于

if( i > j) //evaluates to false
{temp=i;} i=j; j=temp;

如果条件为假,则会出现以下意外结果

If condition is false, there would be unexpected results as below

i=5;
j=10;
temp=0;
i=j;  /* i becomes 10 */
j=temp; /* j becomes 0 */

学习


  1. 尝试将块(if,else,for,do,while)放在 {}

  2. 避免宏

  3. 如果必须使用宏,请使用安全宏,例如:



    #define swap(a,b)do {temp = a; a = b; b = temp; } while(0)


    请注意, while(0)后没有终止分号

#define swap(a,b) do { temp=a; a=b; b=temp; } while(0)

Note that there is no terminating semicolon after while(0)

这篇关于此预处理器指令C / C ++需要说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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