Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » logical vs. binary operators

This thread is locked; no one can reply to it. rss feed Print
 1   2 
logical vs. binary operators
bamccaig
Member #7,536
July 2006
avatar

The confusion comes from modern languages like ECMAScript[1] (and evidently Ruby and others). They do work as Audric described. The operation evaluates to whatever side is last evaluated (for both && and ||, IIRC). It's a little bit of a logical fallacy, I suppose, but it does result in some fun shortcuts. Search for "last value" in this Wikipedia article.

References

  1. The base of JavaScript and ActionScript.
Audric
Member #907
January 2001

I feel very embarrassed... :-[ Looks like the little of Perl that I had, years ago, has contaminated my knowledge of C :(

By the way, I just tested with gcc on win32, and the 'booleans' produced by logical operators seem to be 4-byte size, even when not "mixed" with other data types. I tested using sizeof((1==1)) and normal optimization.

Arthur Kalliokoski
Second in Command
February 2005
avatar

Heh, I remember showing an instructor in the '80's how an Apple II wouldn't accept my "MOVE A TO B" command. He points out that MOVE is a COBOL keyword (yes, studying both languages at the same time).

They all watch too much MSNBC... they get ideas.

ImLeftFooted
Member #3,935
October 2003
avatar

Technically || could return the second element for some given types. Also | can be used as a || for some given types.

template<class C, class FalseT>
C &operator ||&(C &a, C &b, FalseT f = false)
{
  if(a)
    return a;
  if(b)
    return b;
  return f;
}

Uh oh... whats going to happen now? :-X

int i = 0 || 5;

Tobias Dammers
Member #2,604
August 2002
avatar

Audric said:

By the way, I just tested with gcc on win32, and the 'booleans' produced by logical operators seem to be 4-byte size, even when not "mixed" with other data types.

It is pretty common for compilers to base booleans on the platform's native integer type. For x86, that's a 32-bit integer.
The reason is simple: There is little to gain and much to loose by using a smaller data type. There is no speed gain (since the CPU executes most operations on full 32-bit registers anyway), and addressing memory below the register size may cause misaligned memory, which actually decreases RAM performance.

---
Me make music: Triofobie
---
"We need Tobias and his awesome trombone, too." - Johan Halmén

 1   2 


Go to: