3 Comma operator in if condition

Viewed 100

In the C and C++ programming languages, the comma operator is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). But in the below code

#include<iostream>
using namespace std;

int main(){
    int x =2;
    if( x--, --x, x){
        cout<<"First";
    }else{
        cout<<"Second";
    }
    return 0;
}

The output is 'Second' Why?? Please help

3 Answers

x is zero by the time you get to the third element in x--, --x, x, so the else branch is applied.

Note that , is a sequencing point - so there's no undefined behaviour here. Your code is equivalent to the more obvious

int x = 2;
x--;
--x;
if (x){

Lets take even simple usecase,

#include<stdio.h>

int main(){
    int x =2;
    if( 1, 1, 0){
        printf("in if");
    }else{
        printf("in else");
    }
    return 0;
}

As comma will only consider last value. so it will print "in else" here.

But in

#include<stdio.h>

int main(){
    int x =2;
    if( 0, 0, 1){
        printf("in if");
    }else{
        printf("in else");
    }
    return 0;
}

Here it will print in if

  1. built-in comma operator (in contrast to addition e.g) declares a sequence point between its arguments and essentially, evaluates them from left to right. Associativity of this operand is also left to right.
  2. Return value of built-in comma operator is the right most operand(as if returned as decltype(auto)). That means in the expressionif (x--,--x,x) variable x is exactly decremented twice before being evaluted as the last argument (according to 1), and returned as the rightmost operand to builtin comma operator(according to 2) after the evaluation. So if the initial value was 2, the expression evaluates to 0(==false).
Related