Why does someNumber = rand() & 100 + 1; not produce an error?

231 views Asked by At

I was attempting to generate a random number between (1 - 100), and the code to ran, but not doing what I wanted. I noticed I accidentally type &, instead of % with the rand() function, and the compiler did NOT give me an error. What exactly is going on? Why was no error generated? Is the & returning an address? This bug was tricky to find because it's a simple typo that's easy to miss.

Here is the typo:

unsigned int randomNumber = rand() & 100 + 1;

But this is what I mean to type:

unsigned int randomNumber = rand() % 100 + 1;

Here is the code using rand() with & in case you wish to run it:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    srand(static_cast<unsigned int>(time(nullptr)));
    unsigned int randomNumber;
    char again;

    do
    {
        std::cout << "Do you want to generate a random number? (y/n) ";
        std::cin >> again;
        randomNumber = rand() & 100 + 1;
        std::cout << randomNumber << '\n';
    } while (again == 'y');


    getchar();
    return 0;
}
2

There are 2 answers

2
druckermanly On

It's the bitwise and operator. It takes two numbers, then it "ands" their bits.

For example: 3 & 10 is 2.

 0011
&1010
 ----
 0010
0
jkb On

There's no error because it's a perfectly legal expression. The result of the call to rand() is bitwise-anded with the result of 100 + 1.