Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operators and Return in C

Why can't we use return keyword inside ternary operators in C, like this:

sum > 0 ? return 1 : return 0; 
like image 987
nullpointerexception Avatar asked Aug 25 '10 13:08

nullpointerexception


People also ask

Can you use return with ternary operator?

The ternary operator is used to return a value based on the result of a binary condition. It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.

What is ternary operator 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 .

What is ternary operator in C?

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");

Can return statement be used with conditional operators ternary operator in a function?

In a ternary operator, we cannot use the return statement.


2 Answers

return is a statement. Statements cannot be used inside expressions in that manner.

like image 166
Ignacio Vazquez-Abrams Avatar answered Oct 15 '22 18:10

Ignacio Vazquez-Abrams


Because a ternary operation is an expression and you can't use statements in expresssions.

You can easily use a ternary operator in a return though.

return sum > 0 ? 1 : 0; 

Or as DrDipShit pointed out:

return sum > 0; 
like image 24
Wolph Avatar answered Oct 15 '22 20:10

Wolph