Monday, June 21, 2010

C++: Failed Conditions

At ReliSource, we used to have a mailing list called CPP in which we submitted C/C++ related facts/questions (and solutions). I'll share some of those facts/questions in my blog.

Here goes a quick C/C++ problem that I'm sure you will find interesting.

// x is a numeric variable (of built in/intrinsic data type).

if (x > 10)
{
cout << "x is > 10\n";
}
else if (x <= 10)
{
cout << "x is <= 10\n";
}

For some reason, the program didn't output anything, none of the if or else-if was executed. What can be the reason?

You shall find the answer in the comments after a week of this post (if someone already doesn't answer it).

7 comments:

luc said...

Probably because of floating point error, although this highly seems improbabable from the code you given.

We know that usually for double/float you shouldn't do = (equal to checking), you should check with an err margin value. But I am surprised that none of the conditions executed. Maybe somebody was wise enough to override the = or <= operators?

Kaisar said...

@luc:

It's not an operator overriding case.. you actually cannot override the operators which take built-in/intrinsic data types (int or float for example) on both sides which is the case here.

But you are very close.. it's related to floating point error :).

luc said...

If I just consider your question, "none of the if/else if condition executed, why?" .. a reason can be just before the if condition there was a divide by zero error :) and the program's execution path changed ... (failed programming joke :):))

luc said...

On a more serious note,
not answering your question here,
(actually i don't know the answer, except that it's a floating point error which shouldn't have occured..)

just an interesting set of thoughts invoked by your post..

------------------------------
Consider this bit of code..

float x;
x = 11.1;

if (x > 10)
{
std::cout << "x is > 10\n";
}
else if (x <= 10)
{
std::cout << "x is <= 10\n";
}

You can make none of the conditions (if/else if) execute, if you add the following code on top :

class A
{
public:
int operator > (int x)
{
return 0;
}

int operator <= (int x)
{
return 0;
}
} a;

#define float A
#define x a

luc said...

also you need to add the '= 'overloaded operator in class A. I just missed that while posting the comment.

abbasqaisar said...

kaisar sharif here
i could'nt regester my programme even i have the procedure to crack it these are the steps
Step 1: Install the program
Step 2: Backup the original executable
Step 3: Replace with the cracked executable
Step 4: Run the application.
plz help me i don't know how to backup the file plzzzzzzzzz help
my email qsms.sms1@gmail.com

Anonymous said...

float NAN (0.f/0.f) returns false to all tests. I would guess that would be the reason.