[Solved] What does it mean to assign (2, 6, 8) to an integer in C? [closed]


The code

int x = (2, 6, 8);

uses the (very uncommon) comma operator. In C, an expression of the form

expr1, expr2, expr3, ..., exprN

is interpreted to mean “evaluate expr1 and discard its value, then evaluate expr2 and discard its value, …, and finally evaluate exprN and use the value it evaluates to.” So in your case, the expression (2, 6, 8) means “evaluate 2 and discard its value, then evaluate 6 and discard its value, and finally evaluate 8 and use its value.” That means that x gets the value 8.

This code is almost certainly an error as written, since it doesn’t make sense to evaluate 2 and 6 and discard their values. While it’s rare to ever see the comma operator, it’s most commonly used in contexts where the expressions have side effects, as in

for (x = 0; x < 5; x++, i++) { // Increment both x and i

}

while (x = readValue(), x != 0 && x < 15) { // Read a value into x, then check it

}

4

solved What does it mean to assign (2, 6, 8) to an integer in C? [closed]