For the following code:
int main(void) {
int x = 1000, y = 5000;
printf ("%d\n", x, y);
printf ("%d\n", (x, y));
return 0;
}
Output: 1000 5000
Can somebody please explain this?
For the following code:
int main(void) {
int x = 1000, y = 5000;
printf ("%d\n", x, y);
printf ("%d\n", (x, y));
return 0;
}
Output: 1000 5000
Can somebody please explain this?
its about operator precedence
.
in case of (x,y) first statement inside () is evaluated so the last value y is taken as result from (). without () all comma operators have equal precedence so evaluation takes from left to right so x value is taken for printf()
Parentheses make (x, y)
a single expression, composed of x
and y
with a comma operator. The operator evaluates x
, throws the value away, evaluates y
, and make it the value of the expression.
Since evaluating variable x
has no side effect, the expression (x, y)
in this case is equivalent to y
passed by itself:
printf ("%d\n", y);
Note: if your first printf
used a "%d %d"
format string, you would see both x
and y
.
For the first printf, you are just passing a second argument that is being ignored.
For the second, you are invoking the comma operator which evaluates both it's arguments, and returns the value of the second.
What you're seeing here is the evaluation of the C comma operator.
http://en.wikipedia.org/wiki/Comma_operator
The little used comma operator is often used within the third part of a for()
loop to take multiple actions on increment, but technically it's a valid expression anywhere.
In the first call of function printf the number of arguments exceeds the number of format specifiers in the format string
printf ("%d\n", x, y);
In this case the second argument that is y will be ignored. Only x will be outputed. So the output of the call is
1000
In the second call of function printf there is only one argument that is an expression enclosed in parentheses.
printf ("%d\n", (x, y));
This expression is an expression of the comma operator. At first the first operand that is x is evaluated . Its value is ignored. And then the second operand of the expression that is y is evaluated. Its value is used as the result of the full expression. So this function call outputs
5000