why is this giving a syntax error?

int function ( int x)
{
       x ? return 1 : return 0;
}

error C2059: syntax error : 'return'

try,
return x?1:0 ;

try,
return x?1:0 ;

fair enough, but then can't understand why its not working!

What is the reson that you will give, for the following to be wrong

1. a = return 5 ;
2. a = if( b ) ;

The same argument would go for that too.

It's just not legal C, you are expected to write an expression there, not a return statement.

It's just not legal C, you are expected to write an expression there, not a return statement.

so it's incorrect to say a conditional operator can completely replace a 'simple' IF statement?

If thats the way you want to put it then, yes.

the diference is that if statement does not return any thing, but ?: returns the result.

5?a=1:0 ; returns 1, which is assigned to 'a'
thats why you have the error when return 1 canot be assigned to a variable.

This is only a guess, I am not sure what I say is the correct fact.

If thats the way you want to put it then, yes.

the diference is that if statement does not return any thing, but ?: returns the result.

5?a=1:0 ; returns 1, which is assigned to 'a'
thats why you have the error when return 1 canot be assigned to a variable.

This is only a guess, I am not sure what I say is the correct fact.

kewl!:)

the entire thing is a ternary (three-part) operator that evaluates to some value, and you typically use it as a conditional assignment.

(condition) ? value if true : value if false

putting the condition in parentheses is not required, but it may help you to visualize it better. For example, instead of writing a conditional statement like this:

if (myVariable == TRUE)
    newValue = 0;
else
    newValue = -1;

you can write it simply: newValue = (myVariable == TRUE) ? 0 : -1; then you can do whatever you want with the newValue. if all you care to do is return it directly, just put the whole expression as the return value, like any other expression: return (myVariable == TRUE) ? 0 : -1; .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.