understanding printf() in C [duplicate] - c

Please explain the output of this program:
int main()
{
int a,b,c,d;
a=10;
b=20;
c=a,b;
d=(a,b);
printf("\nC= %d",c);
printf("\nD= %d",d);
}
The output which I am getting is:
C= 10
D= 20
My doubt is what does the "," operator do here?
I compiled and ran the program using Code Blocks.

The , operator evaluates a series of expressions and returns the value of the last.
c=a,b is the same as (c=a),b. That is why c is 10
c=(a,b) will assign the result of a,b, which is 20, to c.
As Mike points out in the comments, assignment (=) has higher precedence than comma

Well, this is about operator precedence:
c=a,b
is
equivalent to
(c=a),b
The point is, the "," operator will return the second value.
Thus
c=a,b
assigns a to c and returns b
d=(a,b)
returns b and assigns it to d

The comma operator evaluates all its operands, then yields the value of the last expression.

Related

Question regarding operator precedence in C

I'm starting to learn to program in c, and I thought I was already pretty confident with the precedence of operators, until I did this:
a > b ? c = a : (c = b);
Of course at the first time I didn't use parenthesis on the last sentence, but since that ended up causing compiling issues I searched how to solve that problem on this forum and I read that adding parenthesis could do the job. However, I thought that the expressions inside parenthesis get executed before anything else written in the same line, which would mean that the c = b sentence was executed first and then the ternary operator. I did something similar but easier to read in order to get a better idea of what was happening with this operator precedence thing and tried executing this line:
printf("Number is %d", i) + (i = 5);
I know this expression returns returns a value, but since I don't need it and this isn't a line that I will keep for more than 5 seconds, I won't store it in any variable. What gets my attention in this case is that, when I execute the code, I doesn't show up on the screen with the value 5, but instead it uses the previous value, which means that the computer is just reading it from left to right. When I do:
(i = 5) + printf(Numer is %d, i);
it first does the assignment of i and only after that the printf function is executed. My question is: how does the computer execute an expression that uses operators of different orders of precedence? It clearly doesn't run first the operator with the highest precedence, because in the first printf the value stored wasn't the one assigned on the parenthesis, but it also doesn't just read from left to right because in that case there would be no operator precedence. How does it work?
Parenthesis and operator precedence only dictate how operands are grouped. It does not dictate the order of evaluation.
In this expression:
a > b ? c = a : (c = b);
The three parts of the ternary operator are a > b, c = a, and c = b respectively. This operator also has the property that only one of the second and third clause are evaluated, based on the result of the first. Formally speaking, there is a sequence point between the evaluation of the first clause and of either the second or third. So a > b is first evaluated. If it is nonzero, c = a is evaluated, otherwise c = b is evaluated.
In this expression:
printf("Number is %d", i) + (i = 5);
There is nothing that dictates whether printf("Number is %d", i) or i = 5 is evaluated first. Unlike the ternary operator, there is no sequence point between the evaluation of the operands of the + operator. This expression also has a problem: i is both read and written in the same expression without a sequence point. Doing so triggers undefined behavior. This is also true for:
(i = 5) + printf(Numer is %d, i);
On a side note, this:
a > b ? c = a : (c = b);
Can be more clearly written as:
c = a > b ? a : b;

assignment operators and c

#include <stdio.h>
int main()
{
int i,j;
i=j=(22,23,24);
printf("i:%d",i);
printf("\nj:%d",j);
}
this is giving output of both i,j as 24.
#include <stdio.h>
int main()
{
int i,j;
i=j=22,23,24;
printf("i:%d",i);
printf("\nj:%d",j);
}
and this gives both i,j as 22.
Can someone explain the terminlology behind.
TIA
An assignment operator = has higher precedence than a comma operator ,.
C Operator Precedence - cppreference.com
In this statement
i=j=(22,23,24);
(22,23,24) is firstly calculated. The 22 and 23 are ignored by the comma operator and it is evaluated to 24. Then, the result 24 is assigned to j, and the value is also assigned to i.
On the other hand, in this statement
i=j=22,23,24;
i=j=22 is firstly calculated. This assigns 22 to j, then assign the value to i. After that, the evaluation result of assignment operator 22, and an integer literal 23 are ignored by the comma operator. Finally the expression is evaluated to the value 24, which is also ignored.
A comma separated list of constant expressions does not make much sense. The main purpose of comma operator is to separate assignments - a transparent and conscious side-effect.
With parentheses and two more assignments it groups as:
i = j = (22,x=23,y=24);
Since an expression in parens (E) is a primary expression, this can be hierarchically seen as
i = j = E;
This E consists of three comma separated (sub-)expressions where the last one counts. This is assignment y=24 with result/evaluation 24.
The 22 is thrown away, but x=23 has the obvious side effect.
Normally E would be something like 2*n+1 that does not need parens. Until up to the i = j > 22 ? 23 : 24 (where it gets a bit confusing).
The second one groups:
i=j=22, x=23, y=24;
This starts to make sense now. It is just three assigments on one line. 23 and 24 are not "lost".
The assigment expression i=j=22 itself has one level of recursion; it works right-to-left, which is only natural.
But the examples are more about combining separating comma operators , and grouping parentheses ( ).

How does this return statement with multiple values (variables) works? [duplicate]

This question already has answers here:
What does the comma operator , do?
(8 answers)
Closed 7 years ago.
I am trying to get some understanding about how pass by value & return are happening in C functions. I cam across a piece of code as follows:
#include <stdio.h>
int fun(int ii, int jj)
{
int kk, ll;
kk = ii + jj;
ll = ii * jj;
return (kk,ll);
}
int main()
{
int i=4, j=5, k, l;
k = fun(i, j);
l = fun(i, j);
printf("%d %d\n", k, l);
return 0;
}
Now apparently I am not getting any errors when I am trying to return 2 values through fun().
Also, the value that is returned by fun() is ll i.e 20 (=4*5) and not kk. Further, If I rewrite the return statement as :
return (ll,kk);
the value returned is that of kk ie. 9 (=4+5).
Query: Why this is so?
In your code, in the return statement
return (kk,ll);
you're using the comma operator. By the property of the comma operator, you're not returning two values, rather you're returning the second operand of the comma operator only.
To elaborate, let's check the property of the comma operator, directly quoting the standard, C11, chapter ยง6.5.17, (emphasis mine)
The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.
So, essentially, a return statement like
return (kk,ll);
is same as
return ll;
Hope you can figure out the other case.
That said, the recommended signature for main() is int main(int argc, char*argv[]) or , at least, int main(void).
What do you expect when returning an int? C does not support tuples.
You are using the comma-operator. (ll, kk) is a single expression with the inner expressions (seperated by , - thus the name) being evaluated left to right. All but the rightmost (you can have more than two sub-expressions) results are discarded and the rightmost result is the result of the whole expression. Actually the parenthesis are unnecessary and do not change anything.
You are using the comma operator.
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).

Difference between "int i=1,2,3" and "int i=(1,2,3)" - variable declaration with comma operator [duplicate]

This question already has an answer here:
Why different behavior in two cases 1st. int i = 1,2,3; and 2nd. int i; i = 1,2,3; [duplicate]
(1 answer)
Closed 7 years ago.
int i=1,2,3;
int i=(1,2,3);
int i; i=1,2,3;
What is the difference between these statements? I can't get to any particular reason for it.
Statement 1 Result : Compile error.
'=' operator has higher precedence than ',' operator.
comma act as a separator here. the compiler creates an integer variable 'i' and initializes it with '1'.
The compiler fails to create integer variable '2' as '2' is not a valid indentifer.
Statement 2 Result: i=3
'()' operator has higher precedence than '='. So , firstly, bracket operator is evaluated. '()' operator is operated from left to right. but it is always the result of last that gets assigned.
Statement 3: Result: i=1
'=' operator has higher precedence than ',' operator. so 'i' gets initialized by '1'. '2' and '3' are just constant expression. so have no effect .
It is the comma operator
i = a, b, c; // stores a into i ... a=5, b=2, c=3, i=5
i = (a, b, c); // stores c into i ... a=5, b=2, c=3, i=3
the differing behavior between the first and second lines is due to the comma operator having lower precedence than assignment.

I am getting a strange output in C?

Here is a c program.I am getting a strange output.
When num1=10 and num2=20->
#include<stdio.h>
void main()
{
int num1=10,num2=20;
clrscr();
if(num1,num2)
{
printf("TRUE");
}
else
{
printf("FALSE");
}
getch();
}
Output:
TRUE
when num1=0 and num2=220
Output:
TRUE
But when num1=0 and num2=0:
Output:
FALSE
Why does this happen?
also,what does this given below code mean:
if(num1,num2)
Thanks in advance!
You're using the comma operator. That operator first evaluates its first operand, then drops the result on the floor and proceeds to evaluate and return its second operand.
That's why your program only prints FALSE if num2 evaluates to false in a boolean context (like e.g. 0, 0.0 or NULL).
In:
if(num1,num2)
the last expression overrides all preceeding ones so it's the same as:
if(num2)
since, num2 is 0, you get FALSE.
If you check this out,
http://msdn.microsoft.com/en-us/library/2bxt6kc4(v=vs.71).aspx
the , stands for sequential evaluation, meaning the expressions are evaluated one after another, the last being your num2.
Learn about comma operator in c http://en.wikipedia.org/wiki/Comma_operator.
i=(a,b) means store b in i.
Everything else than 0 in c is true.
so if(3) if (-3) all are true
only if(0) is false
if(num1,num2)
Is a use of the comma operator. The Comma operator calculates the first operand and discards the result then the second operand and returns the result. Thus (a, b) calculates a, calculates b and then returns b.
This should clear up your confusion for the logical cases, in each of them the statement has the effect of looking at the value of b.
if(num1,num2)
is not a syntax error, but it is a logic error. Basically, this will resolve to being only
if(num2)
Only the last variable is evaluated.
I assume what you want is 'if a and b are true'. The comma like you are using means to evaluate just the last variable.
What I think you want is:
if(num1 && num2) /* num1 AND num2 */
You need to use && (logical AND) not a single & (Which is bitwise AND)

Resources