Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd behavior with ternary operation

The following code is supposed to remove the last char of a string and append l (lowercase L) if flip is true or r if it's false.

std::stringstream ss;
ss << code.substr(0, code.size() - 1);
ss << flip ? "l" : "r";
std::string _code = ss.str();

However, when flip is true, it appends 1 and when it's false, it appends 0. How come?

like image 978
Nacib Neme Avatar asked Jan 08 '15 15:01

Nacib Neme


2 Answers

Precedence issue.

ss << flip ? "l" : "r";

means

(ss << flip) ? "l" : "r";

Use

ss << ( flip ? "l" : "r" );
like image 58
ikegami Avatar answered Oct 19 '22 02:10

ikegami


It has to do with operator precedence. << has priority over ? which means flip is appended onto ss first.

The following should lead to the expected behaviour:

 ss << (flip ? "l" : "r");
like image 24
IXI Avatar answered Oct 19 '22 04:10

IXI