Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

|= operator

Status
Not open for further replies.

mrkan

Programmer
Oct 30, 2006
39
0
0
US
What is the difference here between these two lines:

int a = funct();
int a |= funct();

(funct() returns integer value)


Thanks.
 
The latter will but an indeterminate value in a. If a is used after this, the result is unpredictable.

What it is actually doing is

int a = a | funct ();

Problem is a doesn't exist yet so this is actually illegal.

Internally, it will get the value of funct, pop it into a register, create a space for a, pop its value into a register, or the two registers and put the value back into a.
 
True difference: the 1st statement is a correct definition (declare a and inititialize it) but the 2nd one is an incorrect declaration (i.e. a wrong declaration statement;).
 
As already stated, you should never use

Code:
int a |= funct();

but
Code:
int a = 0;
a |= funct();
is perfectly good coding practice. In this case the '|=' operation adds the return value from funct() to what is already in a. What needs to be considered is that in creating variable int a, the memory management functions give (usually 16 or 32 bytes for an int) of memory up for use by this variable from a memory 'pool'. Unfortunately, those few bytes of memory have probably already been used by another variable and then when the variable goes out of scope, returned to the 'pool', still with its previous contents uncleared. By applying the |= operation as you create the variable, you are adding the return value from func() to that random data left over from its (probable) previous use.

The main lesson here I think is ALWAYS initialise your variables to a known value before you use them.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top