Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

BobXRoberts

macrumors newbie
Original poster
Mar 29, 2006
6
0
Hello again! I'm about to ask what may be a silly question- but after half an hour's research the answer still eludes me...

The following code compiles well, of course:

#include <iostream>
using namespace std;
int main () {

int a;
int b;
int c;
cin >> a >> b;
c = a%b;
cout << c;

if (c=0)

{
cout << "Modulo is zero";}

return 0;
}

The code works fine- except when the modulo is zero(say when I divide eight by two), in which case the if test does not seem to detect that the modulo is zero, and refuses to print the string. Neither does it do so if I declare c as a float. This seems rather dodgy to me- a modulo is an integer, and not detecting that an integer is zero seems rather serious! I have the suspiscion tha I am doing something horribly wrong and not noticing...
 

HiRez

macrumors 603
Jan 6, 2004
6,265
2,629
Western US
I think you want if c == 0 (double equals sign). The way you have it, you're assigning 0 to c instead of comparing its value to 0.
 

BobXRoberts

macrumors newbie
Original poster
Mar 29, 2006
6
0
Phweeee-oo. I've really outdone myself there. I noticed that about three minutes after I'd posted, rushed back here in the hope of catching myself, only to find that you helpful person had posted. Cheers! This is what comes from coding eight hours straight... (It's the middle of the night where I am...)

Moral: Be Awake Before Complaining About Faults in Major Programming Languages That Were Around Before you were Born.
 

MarkCollette

macrumors 68000
Mar 6, 2003
1,559
36
Toronto, Canada
BobXRoberts said:
Phweeee-oo. I've really outdone myself there. I noticed that about three minutes after I'd posted, rushed back here in the hope of catching myself, only to find that you helpful person had posted. Cheers! This is what comes from coding eight hours straight... (It's the middle of the night where I am...)

Moral: Be Awake Before Complaining About Faults in Major Programming Languages That Were Around Before you were Born.

A good defensive programming technique is to always do:

Code:
if( 0 == var ) {}

instead of:

Code:
if( var == 0 ) {}

since the compiler will catch it as an error if you accidently do:

Code:
if( 0 = var ) {}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.