The comma operator evaluates all operands from left to right, and the result is the value of the last operand.
In most cases, this is useful for for-loops if you want to do a few actions in the "increment" part, for example (reversing the string)
for (int lower = 0, upper = s.size() - 1; lower < upper; ++lower, --upper) std::swap(s[lower], s[upper]);
Another example where this could be an option (search for all occurrences in a string):
#include <string> #include <iostream> int main() { std::string s("abracadabra"); size_t search_position = 0; size_t position = 0; while (position = s.find('a', search_position), position != std::string::npos) { std::cout << position << '\n'; search_position = position + 1; } }
In particular, they are logical and cannot be used for this condition, since both zero and non-zero can mean that the character was found in the string. On the other hand, with a comma, position = s.find() is called every time a condition is evaluated, but the result of this part of the condition is simply ignored.
Naturally, there are other ways to write a loop:
while ((position = s.find('a', search_position)) != std::string::npos)
or simply
while (true) { position = s.find('a', search_position); if (position == std::string::npos) break; ... }
UncleBens Jan 18 2018-10-18 15:54
source share