ternary operator

I have problems understanding ternary operator. I read basics of how it works many times, and have basics understanding, but still strugle to fully follow throgh the code of it. Does this ternary operator code mean the same as the code below it?


Also how does it work with the return. Does return just give back the variable that x was placed into (if my thinking is correct in second code). meaning if x placed in x, return gives x, if x placed in y, return gives y?
 
 return (x > y) ? x : y;


1
2
3
4
5
6
7
8
9
if (x > y)
	{
		x = x;
	}
	else
	{
		y = x
	}
its just a shortcut for
if (condition) first thing else second thing

there is no assignment inherent in it.

this one says:
if x> y
return x
else
return y

x is not modified at all, nor is y.
Last edited on
> Does this ternary operator code mean the same as the code below it?

No. The ternary operator (aka conditional operator) is an operator; it is used as part of an expression
The if-else construct is just a statement.

This snippet may illustrate the fundamental difference between the two:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
    int a = 5 ;
    int b = 22 ;
    int c ; std::cin >> c ;
    int& r = c < 10 ? a : b ; // reference initialisation requires an lvalue of type int
                              // c < 10 ? a : b is an expression (an lvalue of type int)

    struct A
    {
        // initialise v with 10 if arg is divisible by 3, with 23 otherwise
        A( int arg ) : v( arg%3 ? 23 : 10 ) {} // an expression is required here; the initialiser must be an expression
        const int v ; // note: const, so must be initialised
    };   

    if( a < c ) std::cout << "hello" ; else std::cout << 12345 ; // fine; this is just a statement
    std::cout << ( a < c ? "hello" : 12345 ) ; // *** error *** : incompatible operand types for the expression

}


Topic archived. No new replies allowed.