Odd behavior in triple operation

The following code should remove the last char of the string and add l (lowercase L) if flip is true or r if it is false.

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

However, when flip true, it adds 1 , and when it is false, it adds 0 . Why?

+5
source share
2 answers

Priority issue.

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

means

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

Using

 ss << ( flip ? "l" : "r" ); 
+18
source

This is due to the priority of the operator. << has priority over ? , which means flip added first on ss .

The following should lead to the expected behavior:

  ss << (flip ? "l" : "r"); 
+3
source

Source: https://habr.com/ru/post/1210675/


All Articles