c++ - When/why does (a < 0) potentially branch in an expression? -


after reading many of comments on question, there couple people (here , here) suggest this code:

int val = 5; int r = (0 < val) - (val < 0); // line here 

will cause branching. unfortunately, none of them give justification or why cause branching (tristopia suggests requires cmove-like instruction or predication, doesn't why).

are these people right in "a comparison used in expression not generate branch" myth instead of fact? (assuming you're not using esoteric processor) if so, can give example?

i would've thought there wouldn't branching (given there's no logical "short circuiting"), , i'm curious.

to simplify matters, consider 1 part of expression: val < 0. essentially, means “if val negative, return 1, otherwise 0”; write this:

val < 0 ? 1 : 0 

how translated processor instructions depends heavily on compiler , target processor. easiest way find out write simple test function, so:

int compute(int val) {     return val < 0 ? 1 : 0; } 

and review assembler code generated compiler (e.g., gcc -s -o - example.c). machine, without branching. however, if change return 5 instead of 1, there branch instructions:

...     cmpl    $0, -4(%rbp)     jns     .l2     movl    $5, %eax     jmp     .l3 .l2:     movl    $0, %eax .l3: ... 

so, “a comparison used in expression not generate branch” indeed myth. (but “a comparison used in expression generate branch” isn’t true either.)


addition in response extension/clarification:

i'm asking if there's any (sane) platform/compiler branch likely. mips/arm/x86(_64)/etc. i'm looking 1 case demonstrates realistic possibility.

that depends on consider “sane” platform. if venerable 6502 cpu family sane, think there no way calculate val > 0 on without branching. modern instruction sets, on other hand, provide type of set-on-x instruction.

(val < 0 can computed without branching on 6502, because can implemented bit shift.)


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -