Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does bitwise-or guarantee an evaluation ordering?

Say I have this code:

unsigned int func1();
unsigned int func2();
unsigned int func3();

unsigned int x = func1() | func2() | func3();

Does C++ guarantee that func1() will be called first, then func2(), and then func3()?

Or is the compiler allowed to call the functions in any order it feels like?

Also, is the compiler allowed to implement a short-circuit optimization here if it wants to? (e.g. if func1() returned ~0, could the compiler decide not to bother calling func2() or func3(), because it knows their return values can't possibly affect the value assigned to x?)

like image 919
Jeremy Friesner Avatar asked May 20 '11 23:05

Jeremy Friesner


People also ask

Does order matter in bitwise operations?

Answer. Yes and no. It depends on how many logical statements there are. When there is only one logical statement, it's always going to evaluate the same way, because it's just a single statement.

What is the purpose of bitwise?

A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits. Bitwise operators are used in: Communication stacks where the individual bits in the header attached to the data signify important information.

What are the advantages of using bitwise operations?

Bitwise operations are incredibly simple and thus usually faster than arithmetic operations. For example to get the green portion of an rgb value, the arithmetic approach is (rgb / 256) % 256 . With bitwise operations you would do something as (rgb >> 8) & 0xFF .

Does order matter in bitwise XOR?

Important properties of XOR These are formal mathematical terms but actually the concepts are very simple. This is clear from the definition of XOR: it doesn't matter which way round you order the two inputs. This means that XOR operations can be chained together and the order doesn't matter.


1 Answers

No, there is no guarantee which order the functions will be called in. Unlike ||, | does not imply a sequence point.

All functions in the expression must be called unless the implementation can determine that they have no side-effects and it can determine the result of the expression without actually calling one of the functions. The implementation can do this under the "as if" rule which allows the implementation to perform any optimization which cannot be observed or detected by a conforming program.

like image 144
CB Bailey Avatar answered Oct 23 '22 16:10

CB Bailey