lololol
lololol

Reputation: 13

What's wrong with my ternary `if` expression?

i understand that the conditional operator ? can be used to simplify the if conditional but i'm really having a hard time with it, is it possible to use it as a loop ? for example in the code here it keeps telling me that i can not use r as a function what exactly am i missing ?

#include <iostream>

using namespace std;

#define PI 3.14159

int main () {  
    double r,circle,o;  
    int rmax =0;
    int n;
    cout << "enter the number of  circles:";
    cin >> n;
    (n > 1) ? cin >> r (r > rmax) ? rmax = r : r=r: cout<<rmax; 
}

Upvotes: 0

Views: 103

Answers (1)

Thomas Sablik
Thomas Sablik

Reputation: 16454

The ternary operator (?:) can be easier described using a function:

#include <iostream>

template<typename T>
T &ternary(bool a, T &b, T &c) {
    if (a)
        return b;
    else
        return c;
}

int main() {
    // The behavior is not completely equivalent
    // This example just explains the basic concept of the ternary operator
    std::cout << ternary(true, 5, 2) << '\n';
    std::cout << (true ? 5 : 2) << '\n';
}

The expression condition ? value1 : value2 returns either value1 or value2 depending on condition.

Of course, value1 and value2 can also be complex expressions but you have to remember to handle the returned values.

#include <iostream>

int main() {
    int a;
    std::cout << (true ? a = 5 : 2) << '\n';
}

Both possible values must have the same type.

Your expression would look like:

ternary((n > 1), cin >> r ternary((r > rmax), rmax = r, r=r), cout<<rmax); 

Now the problem should be obvious.

Upvotes: 1

Related Questions