Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
What if a built-in logical or relational operator `returns something other than 1? ....
Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered ``true'' in C? What if a built-in logical or relational operator ``returns'' something other than 1?
✍: Guest
It is true (sic) that any nonzero value is considered true in C, but this applies only ``on input'', i.e. where a Boolean value is expected. When a Boolean value is generated by a built-in operator such as ==, !=, and <=, it is guaranteed to be 1 or 0. Therefore, the test
if((a == b) == TRUE)
would work as expected (as long as TRUE is 1), but it is obviously silly. In fact, explicit tests against TRUE and FALSE are generally inappropriate. In particular, and unlike the built-in operators, some library functions (notably isupper, isalpha, etc.) return, on success, a nonzero value which is not necessarily 1, so comparing their return values against a single value such as TRUE is quite risky and likely not to work.
(Besides, if you believe that
if((a == b) == TRUE)
is an improvement over
if(a == b)
why stop there? Why not use:
if(((a == b) == TRUE) == TRUE)
or even:
if((((a == b) == TRUE) == TRUE) == TRUE)
Given that
if(a == b)
is a perfectly legitimate conditional, so is
#include <ctype.h>
...
if(isupper(c))
{ ... }
since isupper is known to return zero/nonzero for false/true. Similarly, there should not be any reluctance to use code like
int is_vegetable; /* really a bool */
...
if(is_vegetable)
{ ... }
or
extern int fileexists(char *); /* returns true/false */
...
if(fileexists(outfile))
{ ... }
as long as is_vegetable and fileexists() are of ``conceptual Boolean type.'' Alternatives like
if(is_vegetable == TRUE)
or
if(fileexists(outfile) == YES)
are not really any improvement. (They can be thought of as ``safer'' or ``better style,'' but they can also be thought of as risky or poor style. They certainly don't read as smoothly. A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable or function parameter, or as the return value from a Boolean function, but never in a comparison.
2016-02-29, 1217👍, 0💬
Popular Posts:
What is the quickest sorting method to use? The answer depends on what you mean by quickest. For mos...
How do we configure “WebGarden”? “Web garden” can be configured by using process model settings in...
What are some advantages and disadvantages of Java Sockets? Advantages of Java Sockets: Sockets are ...
How To Get the Last ID Assigned by MySQL? - MySQL FAQs - Managing Tables and Running Queries with PH...
.NET INTERVIEW QUESTIONS - How to prevent my .NET DLL to be decompiled? By design .NET embeds rich M...