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?
The return statement is used for returning from a function , you can't use inside ternary operator.
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 .
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.
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!”.
The second and third arguments to the ternary operator are expressions, not statements.
return a
is a statement
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