如何在C preprocessor工作? [英] How does the preprocessor work in C?
问题描述
为什么对于低于code 16的答案吗?任何人都可以解释这个计划的工作?
的#define SQUARE(n)的n * n的
无效的主要()
{
诠释J;
J = 16 /平方(2); 的printf(\\ n J =%d个,J);
残培();
}
如果我们写的一样code像下面,那么答案是4:
//俺们是4,为什么?
#包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;SQUARE的#define(n)的n * n的无效的主要()
{
诠释J;
J = 16 /(方(2)); 的printf(\\ n J =%d个,J);
残培();
}
在preprocessor只是取代了文字,正是因为写的。
那么,宏调用 SQUARE(2)
成为字面上 2 * 2
。
在你的情况,这意味着整个前pression变得 16/2 * 2
,这是因为的计算结果为(16/2)* 2,即16。
宏应始终括号括起来,并有封闭以及每一个参数。
如果我们这样做,我们得到:
的#define SQUARE(N)((N)*(N))
用于替换为 16 /((2)*(2))
,其计算结果为16/4,即4。
周围每个参数的括号使得像东西SQUARE(1 + 1)如预期
工作,没有他们打个电话,如 16 /平方( 1 + 1)
将成为 16 /(1 + 1 * 1 + 1)
是 16/3
,即不是所有你想要的东西。
Why is the answer for the below code 16? Can anybody explain the working of this program?
#define SQUARE(n) n*n
void main()
{
int j;
j =16/SQUARE(2);
printf("\n j=%d",j);
getch();
}
If we write the same code like below, then the answer is 4:
//the ans is 4 why?
#include<stdio.h>
#include<conio.h>
#define SQUARE(n) n*n
void main()
{
int j;
j =16/(SQUARE(2));
printf("\n j=%d",j);
getch();
}
The preprocessor just replaces the text, exactly as written.
So, the macro call SQUARE(2)
becomes literally 2*2
.
In your case, that means the whole expression becomes 16/2*2
, which because of C's precedence rules evaluates to (16/2)*2, i.e. 16.
Macros should always be enclosed in parenthesis, and have each argument enclosed as well.
If we do that, we get:
#define SQUARE(n) ((n) * (n))
which replaces to 16/((2) * (2))
, which evaluates as 16/4, i.e. 4.
The parens around each argument makes things like SQUARE(1+1)
work as expected, without them a call such as 16/SQUARE(1+1)
would become 16/(1+1*1+1)
which is 16/3
, i.e. not at all what you'd want.
这篇关于如何在C preprocessor工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!