37

I wrote the absolute function using ternary operator as follows

int abs(int a) {
 a >=0 ? return a : return -a;
}

I get the following error messages

../src/templates.cpp: In function ‘int abs(int)’:
../src/templates.cpp:4: error: expected primary-expression before ‘return’
../src/templates.cpp:4: error: expected ‘:’ before ‘return’
../src/templates.cpp:4: error: expected primary-expression before ‘return’
../src/templates.cpp:4: error: expected ‘;’ before ‘return’
../src/templates.cpp:4: error: expected primary-expression before ‘:’ token
../src/templates.cpp:4: error: expected ‘;’ before ‘:’ token
../src/templates.cpp:5: warning: no return statement in function returning non-void

If I write like this

return a>=0 ? a : -a;

I don't get any error. What's the difference between the two?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ameen
  • 811
  • 2
  • 12
  • 16

5 Answers5

54

The second and third arguments to the ternary operator are expressions, not statements.

 return a

is a statement

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
  • The first argument to the ternary operator is also an expression, of course. The latter two might be expressions of type `void`, though. – Jonathan Leffler Oct 12 '10 at 19:28
44

Your syntax is incorrect. It should be

if (a >=0)
    return a;
else
    return -a;

or the way you wanted it:

return a >=0 ? a : -a;
Martin York
  • 257,169
  • 86
  • 333
  • 562
Nandit Tiku
  • 583
  • 3
  • 5
24

What's the difference between the two?

One is correct syntax, the other is not.

Gary Willoughby
  • 50,926
  • 41
  • 133
  • 199
  • 1
    Yes, but **why** is it incorrect? Why can't you use ```return``` in the ternary operator? – H-005 Jul 09 '20 at 07:08
  • 2
    @H-005 this is due to language grammar; the ternary operator is written in a specific way that expects expressions not statements – Avrdan Jan 06 '21 at 20:57
11

?: is an operator that takes three expressions and evaluates them in some way to produce a result. return a is not an expression (it's a statement), so your first form doesn't work. It's the same as you can't put return in the arguments of other operators: return a + return b will also not work.

If you want the returns in the separate branches, use if instead:

if (a >=0)
   return a;
else
   return -a;
sth
  • 222,467
  • 53
  • 283
  • 367
9

Return is a statement and cannot be used where a value is expected.

You must use expressions (which usually yield a value) in the three components of the ternary operator.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278