Why can't we use return keyword inside ternary operators in C, like this:
sum > 0 ? return 1 : return 0;
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.
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 .
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");
In a ternary operator, we cannot use the return statement.
return
is a statement. Statements cannot be used inside expressions in that manner.
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;
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