简体   繁体   中英

C++ conversion from int to bool

I want to know if the compiled code of a bool-to-int conversion contains a branch (jump) operation.

For example, given void func(bool b) and int i :

Is the compiled code of calling func(i) equivalent to the compiled code of func(i? 1:0) ?

Or is there a more elaborate way for the compiler to perform this without the branch operation?

Update:

In other words, what code does the compiler generate in order to push 1 or 0 into the stack before jumping to the address of the function?

I assume that it really comes down to the architecture of the CPU at hand, and that some specific processors (certain DSPs, for example) may support this. So my question refers to "conventional" general-purpose CPUs (assuming that this definition is acceptable).

In terms of pure software, the question can also be phrased as: is there an efficient way for converting an integer value to 1 when it's not 0, and to 0 otherwise, without using a conditional statement ?

Thanks

It's not your (compiler user) job too make built-in type conversion efficient. If the compiler is not dumb, it will make that sort of things as close as the CPU representation are.

For the most of the commercial CPU, bool and int are the exact same thing, and if(x) { ... } translate in bit-anding (or bit-oring, whichever is faster: they are normally immediate instructions) x with itself and make a conditional jump after the } if the zero flag is set. (not that this is just a trick to force the zero-flag computation, that is an immediate consequence of the arithmetic unit electronics)

variants are much more a matter of CPU electronics, than code. So don'care about it. if s are not triggered by a bool, but by the last arithmetic operation result.

Whatever arithmetic operation held by a CPU produces a result ans set some flags that represent certain result attributes: if it is zero, if it produced a carry or borrow, if it has an odd or even number of bit set to 1 etc. Resut and Flags are two registers, and can be loaded and stored from/to memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM