I came across a line of code and never thought it might work well. I thought the conditional operator return value and does not work with reference.
Some pseudo code:
#include <iostream>
using namespace std;
class A {
public:
A(int input) : v(input) {};
void print() const { cout << "print: " << v << " @ " << this << endl; }
int v;
private:
//A A(const A&);
//A operator=(const A&);
};
class C {
public:
C(int in1, int in2): a(in1), b(in2) {}
const A& getA() { return a;}
const A& getB() { return b;}
A a;
A b;
};
int main() {
bool test = false;
C c(1,2);
cout << "A @ " << &(c.getA()) << endl;
cout << "B @ " << &(c.getB()) << endl;
(test ? c.getA() : c.getB()).print(); // its working
}
Can someone explain? Thx.
hence in expressions the return statement can not be used in C-language. Show activity on this post. The return statement is used for returning from a function , you can't use inside ternary operator.
Conditional AND The operator is applied between two Boolean expressions. It is denoted by the two AND operators (&&). It returns true if and only if both expressions are true, else returns false.
Conditional operators are used to evaluate a condition that's applied to one or two boolean expressions. The result of the evaluation is either true or false.
Conditional operators return one value if condition is true and returns another value is condition is false.
Your assumption about the conditional operator is wrong. The type of the expression is whatever type the expressions c.getA()
and c.getB()
have, if they have the same type, and if they denote lvalues, then so does the entire expression. (The exact rules are in §5.16 of the C++ standard.)
You can even do this:
(condition? a: b) = value;
to conditionally set either a
or b
to value
. Note that this is C++-specific; in C, the conditional operator does not denote an lvalue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With