913 views
0 votes
0 votes
anyone explain this prog??

 how to output is evaluvated??

int main()
{
    int x = 10, y;

     y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);
    printf("y = %d\n", y);
    printf("x = %d\n", x);

    return 0;
}

2 Answers

Best answer
2 votes
2 votes

In the statement:
y = (a,b,c,d,e);
comma "," operator acts as a sequence point and thus evaluates from left to right and result of the expression is rightmost value.
But the statement,
y = a , b, c;
is same as : (y = a),b,c; because "," has the lowest precedence.

Now in the expression (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++),
First argument is x++, x will be incremented by 1 for the second argument and 10 will be passed in first argument.
So the second argument will have 11 as the value of x.
In third argument x will be incremented by 1(pre-increment), so 12 will be passed in 3rd argument.
The fourth argument will take 12 as the value of x,
The last argument is post-increment, so 'x 'will remain 12 and 'y' will be assigned 12.
After assignment, x will be incremented by 1.
So, the output will be:
x = 11
x = 12
y = 12
x = 13
Comma in C/C++: http://www.geeksforgeeks.org/?p=8482

edited by
0 votes
0 votes

The output will be as follows:

x = 11
x = 12
y = 12
x = 13
 

To understand the program you just need to know two things:

  1. y = x++; will copy the value of x to y first and then increments the value of x by 1
  2.  y = ++x; will increment the value of x by 1 and then copies the value of x to y 

Related questions

1 votes
1 votes
1 answer
1
sid1221 asked Oct 13, 2017
703 views
int main(){unsigned int x = 1;printf("Signed Result %d \n", ~x);printf("Unsigned Result %ud \n", ~x);return 0;}some one give detailed answer ...(mainly how it works )
1 votes
1 votes
2 answers
2
ShiveshRoy asked Mar 25, 2016
2,359 views
Is set difference operator (-) used in relational algebra associative?
2 votes
2 votes
1 answer
4
rupamsardar asked Aug 30, 2023
466 views
#include <stdio.h int f(int x) { if(x%2==0) { return f(f(x-1)); } else return (x++); } int main() { printf("%d",f(12)); ret...