I saw this code:
if (cond) { perror("an error occurred"), exit(1); }
Why would you do that? Why not just:
if (cond) { perror("an error occurred"); exit(1); }
In your example it serves no reason at all. It is on occasion useful when written as
if(cond) perror("an error occured"), exit(1) ;
-- then you don't need curly braces. But it's an invitation to disaster.
The comma operator is to put two or more expressions in a position where the reference only allows one. In your case, there is no need to use it; in other cases, such as in a while loop, it may be useful:
while (a = b, c < d) ...
where the actual "evaluation" of the while loop is governed solely on the last expression.
Legitimate cases of the comma operator are rare, but they do exist. One example is when you want to have something happen inside of a conditional evaluation. For instance:
std::wstring example; auto it = example.begin(); while (it = std::find(it, example.end(), L'\\'), it != example.end()) { // Do something to each backslash in `example` }
It can also be used in places where you can only place a single expression, but want two things to happen. For instance, the following loop increments x and decrements y in the for loop's third component:
int x = 0; int y = some_number; for(; x < y; ++x, --y) { // Do something which uses a converging x and y }
Don't go looking for uses of it, but if it is appropriate, don't be afraid to use it, and don't be thrown for a loop if you see someone else using it. If you have two things which have no reason not to be separate statements, make them separate statements instead of using the comma operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With