Home > Enterprise >  3 Comma operator in if condition
3 Comma operator in if condition

Time:06-08

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

CodePudding user response:

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){

CodePudding user response:

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

  •  Tags:  
  • c
  • Related