in Programming in C
2,142 views
2 votes
2 votes
int main()
{
     int a = 1, b = 2, c = 3;
     printf("%d", a += (a += 3, 5, a));
}

How is this evaluated ?
in Programming in C
2.1k views

4 Comments

Yes
0
0

@Shaik Masthan  sir but on running this code we are getting 8; then how it is undefined as here we use the comma so it will sure about the sequence and result into a = a+3 

 

please correct me

0
0

@lakshaysaini2013

there are two + operators, due to the first + operator, from left side, it is going to undefined behavior.

0
0

2 Answers

1 vote
1 vote
#include <stdio.h>

int main(void) {
	int a = 1, b = 2, c = 3;
	a =a+ 3, 5, a;// Comma (separate expressions) has least precedence in C so a=1+3; so a=4
	a =a+ a; //() has highest precedence are evaluated first so 4+4 see link below
    printf("%d", a);
	return 0;
}

please check the link:https://www.geeksforgeeks.org/c-operator-precedence-associativity/ 

I hope it will clear your doubt.

edited by
0 votes
0 votes

Ok so first let me list out all operators used here..

  1. ()
  2. +=
  3. ,

Now above operator list I wrote, it is as per C's precedence rule here

So first, it let's take () part,

(a+=3,5,a) =>  As we know, comma proceeds in left-to-right, so this is equal to (a=4,5,a),

Now from above we can say a is having value 4 and we have used parenthesis here, it will take last value which is not but a so finally

     a+= a

=> a+=4

=> a=a+4

and we know a=4 hence

=>a = 4+4=8

so answer is 8. 

by

Related questions