#定义成真!假VS的#define TRUE 1 [英] #define TRUE !FALSE vs #define TRUE 1

查看:1112
本文介绍了#定义成真!假VS的#define TRUE 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

暂且不论事实,因为C99的 stdbool.h 已经存在,定义宏在 C 来处理布尔类型有以下有何区别?

Putting aside the fact that since c99 the stdbool.h has existed, when defining macros to handle Boolean types in C is there any difference between the following?

#define FALSE 0

#define TRUE 1       // Option 1 
#define TRUE !FALSE  // Option 2

从这里的活生生的例子,它似乎不有所作为。有没有一种技术的好处要么选择? (不包括事实,即第二个例子将与C ++ 布尔对象更好地工作。)

From the live example here, it doesn't seem to make a difference. Is there a technical benefit to either option? (Not including the fact that the second example would work better with c++ bool objects.)

推荐答案

ISO C和C99都定义了像这样

ISO C and C99 both define ! like so.

逻辑否定运算符的结果!是0,如果值
  它的操作比较,如果不等于0,1其操作数的值
  比较等于0的结果具有int类型。这位前pression!E是
  相当于(0 == E)。

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int . The expression !E is equivalent to (0==E).

所以!0 计算结果为 1 。的给定一个符合标准的C语言编译器的双方你的选择将有同样的结果。另外有没有运行时的点球,编译器会不断的折!0 1 在编译时。

So !0 evaluates to 1. Given a standards compliant C compiler both your options will have the same result. In addition there's no runtime penalty, compilers will constant fold !0 to 1 at compile time.

如果你想利用这逻辑极端,对什么真的还是假的没有假设......

If you want to take this to the logical extreme and make no assumptions about what true or false are...

#define TRUE  (1==1)
#define FALSE (!TRUE)

这始终是真实的,不管语言的优势。例如,在壳0通常被认为是真或不是错误

This has the advantage of always being true no matter the language. For example, in shell 0 is usually considered "true" or "not an error".

这种事情是从时间当C没有在标准商定一个时代错误。例如, code完成的当它出版早在1993年有你的C编译器不会成为ISO标准,stdbool.h并不存在一个很好的机会,提倡本369页。 code完全也意为通晓多国语言的程序员在许多不同语言的工作。有些人,像贝壳和Lisp,定义不同的真理。

This sort of thing is an anachronism from a time when C did not have an agreed upon standard. For example, the first edition of Code Complete advocates this on page 369. When it was published back in 1993 there was a good chance your C compiler was not going to be ISO compliant and stdbool.h did not exist. "Code Complete" is also intended for the polyglot programmer working in many different languages. Some, like shell and Lisp, define truth differently.

这篇关于#定义成真!假VS的#define TRUE 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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