Here's the code:

#include<iostream.h>
int test();
int main()
{
	cout<<test();
	return 0;
}

int test()
{
	int a=1;
	a==1? return 1: return 0;
}

Could anyone please help me by telling me why VC++ 6.0 rejects this piece of programming code? Is the line" a==1? return 1: return 0;" grammatically wrong? Thank you very much in advance!

I'm pretty sure you can only use that in the form of condition == a ? x = 1 : x = 2;

double posted for some reason.

try :

return ( a == 1 ? true : false );

Sorry for not replying earlier. Thank you sfuo and firstPerson. And it worked to put it like

return ( a == 1 ? true : false )

Thank you very much firstPerson! But I'm still kinda wondering why it didn't work the way I put it in the first place.

Well... think... What exactly is the value of "return 1"? That doesn't evaluate to an rvalue.

Sorry for not replying earlier. Thank you sfuo and firstPerson. And it worked to put it like

return ( a == 1 ? true : false )

Thank you very much firstPerson! But I'm still kinda wondering why it didn't work the way I put it in the first place.

Lets look at this code again :

a == 1 ? return 1; return 0;

In between ? : operator meaning in :

? <here> : <here> ;

could only be a value, so you cannot have return statements
or anything else;

thus you need to wrap everything with the return statement
so it would work :

return ( a == 1 ? 1  : 0 );

So the inside part gets executed, and evaluates to either 1 or 0
then all you have left is either return 1 or return 0.

But why did this work?

a==1? cout<<"1": cout<<"0";

But why did this work?

a==1? cout<<"1": cout<<"0";

because thats still returning a value;

cout<<"A", mean A goes into the stream and then cout is returned .

with your :

a == 1 ? return 1 : return 0;

does not return a value for that expression so it does not work
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.