简体   繁体   中英

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?

Precedence issue.

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

means

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

Use

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

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");

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