Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the output different?

Tags:

c

Please explain me why it behaves differently.

  int main() {
    int p;
    p = (printf("stack"),printf("overflow"));
    printf("%d",p);
    return 0;
  }

This gives the output as stackoverflow8. However , if I remove the paranthesis , then :

p = printf("stack"),printf("overflow"); gives the output as stackoverflow5

like image 982
h4ck3d Avatar asked Jul 16 '12 18:07

h4ck3d


1 Answers

The Comma Operator

The comma operator has lower precedence than assignment (it has a lower precedence than any operator for that matter), so if you remove the parentheses the assignment takes place first and the result of the second expression is discarded. So...

int a = 10, b = 20;
int x = (a,b); // x == 20
int y = a,b;   // y == 10
// equivalent (in terms of assignment) to
//int y = a;

Note that the third line will cause an error as it is interpreted as a re-declaration of b, i.e.:

int y = a;
int b;

I missed this at first, but it makes sense. It is no different than the initial declaration of a and b, and in this case the comma is not an operator, it is a separator.

like image 70
Ed S. Avatar answered Oct 11 '22 06:10

Ed S.