#include <stdio.h>
int main(void) {
int i = 5;
i = (i, ++i, 1) + 1;
printf("%d\n", i);
return 0;
}
I'm Newbie who is studying about the Undefined Behavior.
I was experimenting with this and that with operators, and I made this code If you run the code, you get 2, but in the code I made, there's no decreasing operator, so you don't get 2. Why did I get 2?
And if you execute that, you get this warning. Why?
px.c:5:8: warning: left-hand operand of comma expression has no effect
[-Wunused-value] i = (i, ++i, 1) + 1;
^
To understand the code, you need to see a comma in (i, ++i, 1).
the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). Because it discards its first operand, it is generally only useful where the first operand has desirable side effects. If the side effect to the first operand does not takes place, then the compiler may generate warning about the expression with no effect.
That's what it says. If you interpret it, and
are operators that receive two operands
After calculating the first operands, discard the results and return the value calculated for the second operands.
Before we move on to the question,
To make it easier to explain, we will temporarily add numbers to (i, ++i, 1) + 1;
in order of i.
(i1, ++i2, 1) + 1;
If you write this process differently
i; // evaluate i and discard results -> No impact
Evaluate ++i; // ++i and discard the result. i from 5 becomes 6
i = 1 + 1; // Add last operand 1 and 1 outside parentheses
© 2024 OneMinuteCode. All rights reserved.