0

The below code gives a compiler error:--> rough.cpp:6:30: error: operands to ?: have different types 'short int' and 'const char*'

int main() {
    for (short i {10}; i <= 100; i += 10) {
        cout<<((i % 15 == 0) ? i : "-")<<endl;
    }
    return 0;
}

This code compiles without any error or warning:

int main() {
    for (short i {10}; i <= 100; i += 10) {
        cout<<((i % 15 == 0) ? i : '-')<<endl; // error line
    }
    return 0;
}

And shows the below output:

    45
    45
    30
    45
    45
    60
    45
    45
    90
    45

Can anybody please explain what's happening and what's the difference between the two ?

As I want the expected output to be:

-
-
30
-
-
60
-
-
90
-
Rishi K.
  • 111
  • 1
  • 8
  • 1
    Perfect situation to use an `if` instead of a `?:`. For the `?:`, the true-case-expression and false-case-expression need to be the same type. So the `char` is being promoted to a number for the character value. – Eljay Dec 08 '19 at 15:25

3 Answers3

2

Sometimes the best solution is the simplest solution. In this case you cannot use the ternary operator ?: because you do not have the same return type. Because your first return is an int the '-' that is your else becomes an int, too.

int main() {
    for (short i {10}; i <= 100; i += 10) {
        if(i % 15 == 0)
        {
            cout << i << endl;
        }
        else
        {
            cout << '-' << endl;
        }
    }
    return 0;
}
bhristov
  • 3,137
  • 2
  • 10
  • 26
  • But the in the 2nd code we are returning `i` and `'-'`, which compiles without any error or warnings ! – Rishi K. Dec 08 '19 at 16:48
1

The operands to the conditional operator have to be either the same type or convertible to some common type. There's a long list of rules about this on cppreference but what's happening here is that i, a short int is being converted to a char. Also, an int and char const* do not have a common type and thus give an error.

You want i to be printed as a string.

((i % 15 == 0) ? to_string(i) : "-")
David G
  • 94,763
  • 41
  • 167
  • 253
0

The opeands must have the same type or a common type:

If the operands have different types and at least one of the operands has user-defined type then the language rules are used to determine the common type. (See warning below.)

In your first example you have a string(const char*) which has no common type with int.

While in the second example you have a char the can be converted to an int.

Oblivion
  • 7,176
  • 2
  • 14
  • 33