views:

423

answers:

6

ill have an if statement

if (int1 < int2)
{}
else
{}

I want the else statement to run if both int1 and int2 are 0..

+11  A: 

No. 0 is not less than 0.

How about using an else if statement?

if (int1 < int2)
{
}
else if (int1 == 0 && int2 == 0)
{
}
Zach Johnson
+5  A: 

(0 < 0) should logically return false, as between two equal numbers, one can not be less than the other. (0 <= 0) would return true.

mvid
+1  A: 

No, (0<0) returns false.

It's difficult to understand the logic you propose in the context of the presented code.

spender
+3  A: 

Currently your else clause will run when both ints are 0.

if you want 0s to be treated the same as int1 < int2 then

if( (int1 < int2) || (int1 == 0 && int2 ==0) )

but if you just want 0 < 0 to go to the else, it will...

or perhaps you have some code that you think should be going to your "else", but is entering your "if", but can't work out why so are wondering if 0 < 0? In which case, something else is likely going on in your code.

Keith Nicholas
+1  A: 

Of-course, 0==0 and NOT 0<0 or 0>0

In compiled languages such a c# you need to use comparison operator for each variable as stated in the above answers

if (int1 < int2)
{
}
else if (int1 == 0 && int2 == 0)
{
}

But, if your case is of some interpreted language such as python, you can use a simple inline comparison

if int1<int2:
     print "Less"
elif int1==int2==0:
     print "Equals to 0"
Shoaib
+8  A: 

There are several answer to your immediate question, and plenty of other answers on this page. But there's a larger question that hasn't been addressed yet: why are you asking this question to a web forum, no matter how many expert programmers populate it?

There is an excellent tool at your disposal for automatically answering such questions, and you use it all the time: your C compiler! You just have to phrase the question correctly.

If there's something you don't understand, try putting together a small program to test out some logic and see what happens. Just keep around a simple template (I like ~/tmp/hello_world.c). When you have a question, just make a copy (say, ~/tmp/zerotest.c), add some feature you want to try out (like printf("Answer: %d\n", 0 < 0);), and run it until you understand what's going on.

I do this all the time. Even when I'm working on another project, sometimes I pull chunks of logic out into a little file and play around with it there until I understand. That's what this is about: finding an efficient way to teach yourself a language. Don't be afraid to experiment. It's extremely unlikely you will slap something together that will destroy your system. And even if that happens, I'm sure you can learn something from that experience too.

Get in the habit of experimenting. It's a skill you'll use for the rest of your programming career.

Karmastan