As I've learned that the conditional operator (ternary operator "?") guarantees the order of the evaluation of its operands I want to know whether assigning to a variable the return of ?
where this variable is used in one of its two exprs. be a UB or not. Here is what I have:
I've written this program that tries to convert a string into an integer depending on whether the string str
contains a valid numeric character e.g: +-.0123456789
, So I've used std::stoi
combined with std::string::find_first_of
and conditional operator in one expression:
std::string str = "a^%^&fggh67%$hf#$";
std::size_t pos = 0;
auto val = (((pos = str.find_first_of("0123456789.+-")) != std::string::npos) ?
std::stoi(str.substr(pos)) : -1);
std::cout << val << std::endl; // 67
str = "a^%^&fggh__#$!%$hf#$";
pos = 0;
val = (((pos = str.find_first_of("0123456789.+-")) != std::string::npos) ?
std::stoi(str.substr(pos)) : -1);
std::cout << val << std::endl; // -1
As you can see the piece of code looks to work fine, I know that if value -1
was accidentally found in str
, we don't know whether val
holds -1
of successful operation or failure (? operator). But I want to know only whether this code which I've written has UB or not?
- Thanks to members who guided me in the previous topic which was UB and I've corrected it know.