2

I came across a code snippet which used a statement int k=(a++,++a) in it. I don't understand which type of statement is this (a++,++a) and how it will be evaluated. Why is the bracket is used here? Is it a function call?

Here is the code.

#include <stdio.h>
int main(void) {
    int a=5;
    int k=(a++,++a);
    printf("%d\n",k);
    return 0;
}

The output I get is 7 — why is that?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
asad_hussain
  • 1,959
  • 1
  • 17
  • 27
  • Are you sure the code is? int k=(a++, ++a); does the source code compile? – Leonidas Menendez Jul 23 '16 at 04:56
  • 1
    yes,and the o/p comes as `7` – asad_hussain Jul 23 '16 at 04:57
  • 3
    @LeonidasMenendez I'm quite sure that's written correctly. He's using the comma operator. – WhozCraig Jul 23 '16 at 04:58
  • 2
    Thanks, i think that resolves the mystery, check this: http://stackoverflow.com/questions/54142/how-does-the-comma-operator-work – Leonidas Menendez Jul 23 '16 at 05:09
  • In retrospect, [SO 54142: How does the comma operator work?](http://stackoverflow.com/questions/54142/how-does-the-comma-operator-work) might have been a better choice for duplicate. The 'undefined behaviour' option (my choice) covers a lot of common abuses of `++`, but actually the code is well-formed, if a bit eccentric. – Jonathan Leffler Jul 23 '16 at 05:43
  • @JonathanLeffler It may be well formed, but it's too similar to undefined behavior for my tastes. May as well avoid it. – PC Luddite Jul 23 '16 at 06:45

2 Answers2

6

It's not a function call.

This is an example of using the comma operator, which evaluates each expression from left to right and returns the result of the rightmost expression. It's the same as writing

a++;
k = ++a;

If it had been written

k = a++, ++a;

then it would have been parsed as

(k = a++), ++a;

and evaluated as

k = a++;
++a;
John Bode
  • 119,563
  • 19
  • 122
  • 198
0

Yes you are right; that's why the following code

int main(void) {
    int y=1,x=0;
    int l=(y++,x++)?y:x;
    printf("%d ",l);
    return 0;
}

produces 1 as output.

The value of (y++,x++) returns x i.e the rightmost expression and hence the value of l becomes 1.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
asad_hussain
  • 1,959
  • 1
  • 17
  • 27