1

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?

Andrew Boyley
  • 37
  • 2
  • 8

2 Answers2

3

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.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

Found a geeks for geeks article on it here

Andrew Boyley
  • 37
  • 2
  • 8