简体   繁体   English

此预处理程序指令C / C ++所需的解释

[英]Explanation needed for this pre-processor directive 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;
}

Output i am getting is: 10 0 0 我得到的输出是:10 0 0

Please someone explain how is it working. 请有人解释它如何工作。

Code below 下面的代码

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

Becomes 成为

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

which is equivalent to 相当于

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 */

Learnings 学问

  1. Try to put blocks (if, else, for, do, while) inside {} 尝试在{}内放置块(如果是,则为做某事,同时做)
  2. Avoid macros, prefer functions 避免使用宏,喜欢使用函数
  3. If you must use macros, use safe macros, for ex: 如果必须使用宏,请使用安全宏,例如:

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

Note that there is no terminating semicolon after while(0) 请注意, while(0)之后没有终止分号。

Expanding the macro, you get: 扩展宏,您将得到:

if (i > j)
   temp = i;
i = j;
j = temp;

This is why seasoned c-programmers wrap macro bodies in do{...}while(0) . 这就是为什么经验丰富的c程序员在do{...}while(0)包装宏体的原因。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM