Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return statement in ternary operator c++

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?

like image 876
ameen Avatar asked Oct 12 '10 19:10

ameen


People also ask

Can we use return statement in ternary operator in C?

The return statement is used for returning from a function , you can't use inside ternary operator.

Does ternary operator need return?

The ternary operator consists of a condition that evaluates to either true or false , plus a value that is returned if the condition is true and another value that is returned if the condition is false .

Can we use return in conditional statement?

The return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements.

Can ternary operator return string?

Ternary operator values The values part of the ternary operator in the above example is this: “This is an even number!” : “This is an odd number!”; In the example above, if the condition evaluates to true then the ternary operator will return the string value “This is an even number!”.


Video Answer


1 Answers

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

 return a 

is a statement

like image 195
The Archetypal Paul Avatar answered Sep 21 '22 12:09

The Archetypal Paul