What is wrong with me that this code
if (intro())
return 0;
looks like it shouldn't work?It doesn't have a condition, does it? How is that if statement different than "if(1)" You have to specify what is supposed to equal 1, don't you? Argh.
Why does this C++ code work?
No, you don't.
In C and C++ (and many other languages) the condition of the "if expression" is that it evaluates to either true or false, where "false" is anything that equals zero (0) and "true" is anything non-zero.
So I can write:
if (1) { cout %26lt;%26lt; "this is always true" %26lt;%26lt; endl; }
or
if (! 0) { cout %26lt;%26lt; "this is always true (i.e. never false)" %26lt;%26lt; endl; }
or
int myfunc() { return 1; }
if ( myfunc() ) { cout %26lt;%26lt; "this is always true" %26lt;%26lt; endl; }
When you test for something being equal to 1 or zero or whatever, the result is either 0 (not equal) or non-zero (equal). There is no guarantee that the result will be 1 if it is equal.
By the way, you can use an equality comparison without it being in an if or while:
x = (11 == 22);
cout "x is " %26lt;%26lt; x %26lt;%26lt; endl;
y = (100 == 100)
cout "y is " %26lt;%26lt; y %26lt;%26lt; endl;
Reply:Well, your statement looks like it's in a method (or function).
First, your statement is a complete statement. Yes, it does have a condition. The condition is intro(). If the function intro() returns true (or some integer other than 0), then the "return 0" will be executed. If the function intro() returns false (or the value 0), nothing will be executed since the "if" statement does not have an "else".
Given your function intro() works, your statement will work.
"if (intro())" and "if (1)" are only different as to how the expression, intro() or 1, are evaluated. The value 0 is represents false and a non-zero value or 1 represents true.
You could have "if (intro() == 1)" or "if (1 == 1)". In both cases, the expressions are "true".
Simply 0 is false and 1 is true.
Reply:The condition is on what "intro" does. It could return various things; the language defines which of these are considered "true" in this context.
Reply:the intro() function will return a boolean/ integer value which is equal to 1. That is if the function definition is like the code below the intro() function is equal to 1.
int intro(){
return 1;
}
Reply:is it recursion?
int intro()
{
if(intro())
return 0;
}
it should be infinte loop irrespective of value returned by intro().
Reply:That's easy. Every function gives a return value upon success or failure. So does intro(). That return value is what's evaluated as true or false in your if statement.
daffodil
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment