Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional operator can return reference?

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.

like image 685
Orunner Avatar asked Jan 09 '13 11:01

Orunner


People also ask

Can return statement be used with conditional operators?

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.

What is the return type of conditional operators?

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.

What does the conditional operator do?

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.

What does conditional operator return in C?

Conditional operators return one value if condition is true and returns another value is condition is false.


1 Answers

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.

like image 150
Fred Foo Avatar answered Oct 05 '22 08:10

Fred Foo