Why use boolean literals in logical tests?

This is a discussion on Why use boolean literals in logical tests? within the C# Programming forums, part of the General Programming Boards category; Ok, I've seen this enough to assume there is some benefit or reason for this style. When a condition must ...

  1. #1
    Registered User Strider's Avatar
    Join Date
    Aug 2001
    Posts
    149

    Why use boolean literals in logical tests?

    Ok, I've seen this enough to assume there is some benefit or reason for this style.

    When a condition must be tested in code it is not that uncommon for someone to have
    code like this:

    Code:
    if ( var == true)
        //operation
    My question is this. Why not just use code like this:

    Code:
    if (var)
        //operation
    The clarity seems good for negating a condition better than using the "not" operator "!".

    I think that:
    Code:
    if (var == false)
    is more readable than:
    Code:
    if (!var)
    But of course it would be really confusing to see:
    Code:
    if ( (var == false) == true )
    Which isn't too different IMO from
    Code:
    if ( var == true)
    I mean "true" is the only condition that an "if" statement will trigger off of so to me it doesn't add too much value to clarify that.

    I believe that some classes taught like "C" encourage explicit testing because the C language treats *anything* but zero as true which might not be logically what you are trying to do and there is no "bool" object which can only be true or false.

    In C if a "TRUE" constant is defined as 1 and "FALSE" as 0 then testing for equality against the constant "TRUE" is more deterministic in many cases than using boolean logic. In C# and Java I haven't seen this *as much*.

    Where library designers have provided good method names such as "File.exists" it looks particularly akward to include the "==true" test.

    Does anyone know of any differences (in C#) between the two styles?

    David
    Last edited by Strider; 07-21-2003 at 05:46 PM.
    One Ring to rule them all, One Ring to find them,
    One Ring to bring them all and in the darkness bind them
    In the Land of Mordor where the Shadows lie.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Novice needs help
    By ghaasemi in forum C++ Programming
    Replies: 9
    Last Post: 05-30-2009, 09:20 AM
  2. Logical Operators in C++
    By Flecto in forum C++ Programming
    Replies: 4
    Last Post: 05-15-2009, 08:17 AM
  3. Replies: 4
    Last Post: 04-02-2004, 07:30 PM
  4. Use struct to create a boolean type
    By skyglin in forum C Programming
    Replies: 6
    Last Post: 06-18-2003, 09:21 PM
  5. Logical Error
    By gardenair in forum C Programming
    Replies: 2
    Last Post: 04-06-2003, 05:18 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21