|
-
April 20th, 2004, 03:15 PM
#1
Quiz
You never set bool Even to false, anything other than 0 is true.
#include "stdafx.h"
bool Even( int );
int main()
{
if( Even(21) ) {
bool Even = true;
}
if (Even) {
std::cout << "Number is even!\n";
}
return 0;
}
bool Even( int nbr )
{
bool answer;
if ((nbr % 2) == 0)
answer = true;
else
answer = false;
return answer;
}
-
April 20th, 2004, 03:30 PM
#2
Re: Quiz
Code:
if (Even) {
std::cout << "Number is even!\n";
}
if(Even) is always true since Even is the address of function "Even" in the scope in which it is used, which is always non-zero !!
-
April 20th, 2004, 04:10 PM
#3
Roger65 -
Ah, I picked a bad example program. I should have reversed my if statement to make it clearer.
Consider this though -- if you change the listing so the if statement does the following:
if( !(Even(21)) ) {
bool Even = false;
}
you will also find that the "true" statement will always be printed.... SO even when the bool Even variable is set to false, the
if (Even)
statement that follows will resolve to true .
The reason is as as Kirants stated... scope and naming.
Brad!
Full listing reversed:
Code:
// This listing has the same issue....
#include "stdafx.h"
bool Even( int );
int main()
{
if( !(Even(21)) ) {
bool Even = false;
}
if (Even) {
std::cout << "Number is even!\n";
}
return 0;
}
bool Even( int nbr )
{
bool answer;
if ((nbr % 2) == 0)
answer = true;
else
answer = false;
return answer;
}
-----------------------------------------------
Brad! Jones,
Yowza Publishing
LotsOfSoftware, LLC
-----------------------------------------------
-
April 22nd, 2004, 12:06 PM
#4
The "Even" in the second if statement points to the function bool Even( int ); which always exist so is always true.
The reason for this is that the scope for the variable "bool Even" is inside of the first if statement. It will only be instantiated and then destroyed when and if the number to be tested is even.
So by the time it gets to the second if statement, the "bool Even" variable doesn't exist anymore.
And if the number to be tested is false, well "bool Even" variable would never have been created.
Last edited by smakadia; April 22nd, 2004 at 12:08 PM.
-
April 27th, 2004, 03:48 PM
#5
Hi,
Looking at the code the simplest answer is:
Code:
#include <stdio.h>
bool IsEven(int num);
void main()
{
if(IsEven(21))
printf("Number is Even!\n");
else
printf("Number is Odd!\n");
}
bool IsEven(int num)
{
return !(num % 2);
}
Or you could have possibly used the following if you wanted to create the additional boolean variable:
Code:
#include <stdio.h>
bool IsEven(int num);
void main()
{
bool Even = IsEven(21);
if(Even)
printf("Number is Even!\n");
else
printf("Number is Odd!\n");
}
bool IsEven(int num)
{
return !(num % 2);
}
Best Regards,
Lea Hayes
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|