Search code examples
c++charcoutternary

Why does cout print the ascii value of a char when used with a ternary and int?


Why does this code produce 42012 instead of *012? I can see that it is converting the asterisk to its ASCII value but why?

    vector<int> numbers = {-1,0,1,2};
    for(int num: numbers){
        cout << (num == -1 ? '*' : num); //42012
    }

    for(int num: numbers){
        if(num == -1) cout << '*'; //*012
        else cout << num;
    }

If I use a normal if else statement it works. Why?


Solution

  • The ternary expression returns the "common type" of its true part and false part, and the common type between char and int is int, so '*' is promoted to int.