我们可以删除的参数左右的括号中C宏定义? [英] Can we remove parentheses around arguments in C macros definitions?
问题描述
http://c-faq.com/style/strcmp.html ,我学会了以下方便的宏:
的#define STREQ(S1,S2)(STRCMP((S1),(S2))== 0)
我想知道为什么在这个宏所使用这么多的括号。每次服括号目的还是这个宏使用没有任何用处多余的括号?
我们能删除括号周围 S1
和 S2
,使宏这样的?
的#define MyStreq(S1,S2)(STRCMP(S1,S2)== 0)
的 MyStreq
宏似乎为我的工作很好地为 STREQ
。
的#include<&string.h中GT;
#包括LT&;&stdio.h中GT;的#define STREQ(S1,S2)(的strcmp((S1),(S2))== 0)
的#define MyStreq(S1,S2)(的strcmp(S1,S2)== 0)诠释的main()
{
的printf(%D \\ n,STREQ(富,富),MyStreq(富,富));
的printf(%D \\ n,STREQ(狐狸精,富),MyStreq(狐狸精,富));
的printf(%D \\ n,STREQ(富,狐狸精),MyStreq(富,狐狸精));
返回0;
}
从code的输出上面:
1
0 0
0 0
你能想象这些宏其中 STREQ
只做一所期望的,但 MyStreq
没有任何使用<? / p>
下面是一个比较愚蠢的例子,但它确实有一个不同的结果:
的#define STREQ(S1,S2)(STRCMP((S1),(S2))== 0)
的#define MyStreq(S1,S2)(的strcmp(S1,S2)== 0)
#定义S1富,嗒嗒诠释主(){
STREQ(S1,嗒嗒); //编译并比较平等的。
MyStreq(S1,嗒嗒); //编译器错误。参数太多。
}
From http://c-faq.com/style/strcmp.html, I learned the following convenience macro:
#define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
I want to know why there are so many parentheses being used in this macro. Is each parenthesis serving a purpose or is this macro using redundant parentheses that serve no purpose?
Can we remove the parentheses around s1
and s2
and make a macro like this?
#define MyStreq(s1, s2) (strcmp(s1, s2) == 0)
The MyStreq
macro seems to work for me as nicely as Streq
.
#include <string.h>
#include <stdio.h>
#define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
#define MyStreq(s1, s2) (strcmp(s1, s2) == 0)
int main()
{
printf("%d %d\n", Streq("foo", "foo"), MyStreq("foo", "foo"));
printf("%d %d\n", Streq("fox", "foo"), MyStreq("fox", "foo"));
printf("%d %d\n", Streq("foo", "fox"), MyStreq("foo", "fox"));
return 0;
}
Output from the code above:
1 1
0 0
0 0
Can you imagine any usage of these macros where Streq
does what one would expect but MyStreq
does not?
Here's a relatively dumb example, but it does have a different result:
#define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
#define MyStreq(s1, s2) (strcmp(s1, s2) == 0)
#define s1 "foo", "blah"
int main() {
Streq(s1, "blah"); // Compiles and compares equal.
MyStreq(s1, "blah"); // Compiler error. Too many parameters.
}
这篇关于我们可以删除的参数左右的括号中C宏定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!