Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the result of a modulo operation be used in an if statement directly?

I'm doing a challenge from a book and it's asking me to create a loop that counts down from 20 to 0 and has me print a message for each number. However, it's asking me to print out a special message for each number divisible by 5. I have seen certain examples including this one:

if (number%5==0)
{
    //your code here
}

I get what the modulo is doing, but why does this code have ==0 after it? For example, why not just code it like this:

if (number%5)
{
    //your code here
}
like image 625
Chris Smith Avatar asked Oct 04 '22 22:10

Chris Smith


1 Answers

Because number%5 is an integer between 0 and 4, while number%5==0 is a boolean. Unlike languages like C/C++ where integers can be considered booleans (0 -> false, 1 -> true for example), in C# the condition of an if must be a 'real' boolean.

(Even if C# let you use an integer in an if condition, your suggested change to the code is incorrect. The former piece of code would run your code if number%5 is 0, the latter piece of code would run your code if number%5 is NOT 0.)

EDIT: As Eric Lippert says in the comments, an alternative to using a bool in an if condition is to use something that implements implicit operator bool as a cast or implements operators true and false, such as http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx . But as far as I can tell, no primitives besides bool satisfy either of these.

like image 113
Patashu Avatar answered Oct 07 '22 17:10

Patashu