0
#include<stdio.h>

int main(void) {
    int i=(1,2,3,4);
    printf("%d",i);
    return 0;
}

When I'm given an online technical mock test I came to this question. Firstly I think there is an compilation error in line int i=(1,2,3,4); but I was wrong. I don't know why the output of this question is 4.

msc
  • 32,079
  • 22
  • 110
  • 197
Harrish Kumar
  • 128
  • 2
  • 10

2 Answers2

2

Here, (1,2,3,4); is a sequence of expressions, separated by commas, which evaluates to the last expression.

C11 §6.5.17 Comma operator:

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.

msc
  • 32,079
  • 22
  • 110
  • 197
1

() has higher presedence than = and result of () is the last element which is 4 in your example. Than = operation will be done

onur aslan
  • 253
  • 3
  • 8
  • Clear explanation. Anyway GCC give you a warning about this `left-hand operand of comma expression has no effect` – Michi Oct 13 '17 at 17:26