Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behaviour of ternary operator in C++

The following is snippet from code that I've written:

int n,i,j;
map<int,int>mp;
vector<int>vec;
cin>>n;
for(i=0; i<n; i++)
{
    cin>>j;
    mp[j]==0? mp[j]=1,vec.push_back(j): mp[j]=1;
}

For the second line inside for loop, CodeBlocks-16.01 version shows the following error:

second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'

But when I change the line to:

mp[j]==0? vec.push_back(j), mp[j]=1: mp[j]=1;

There is no error. What is the issue with following line?

mp[j]==0? mp[j]=1,vec.push_back(j): mp[j]=1;
like image 774
emdadul_islam Avatar asked Mar 02 '23 11:03

emdadul_islam


1 Answers

To understand the error, let's take a look the operands to the conditional operator.

The second operand:

mp[j]=1, vec.push_back(j)

The operand is two expressions separated by the comma operator.
The way the comma operator works here is that it evaluates mp[j]=1 which results in value 1, it discards the value and evaluates the next expression vec.push_back(j) which returns void.

Hence the final value of whole second operand is of type void (This is what the error says).

The third operand:

mp[j]=1

This expression evaluates to 1, which is of type int. (Thus it is not void or thrown-exception, and that is what the error says).

When you change the second operand:
In the expression

vec.push_back(j), mp[j]=1

vec.push_back(j) evaluates to void, this value is discarded and then mp[j]=1 evaluates to 1 which is type int. Now both operands are int, hence no error.

like image 105
Kashinath Patekar Avatar answered Mar 16 '23 14:03

Kashinath Patekar