-1

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;
}
user3840170
  • 26,597
  • 4
  • 30
  • 62
  • Sidenote: You can do this more directly with [`std::uniform_int_distribution`](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) from the random library. See the example at the bottom. – user4581301 Oct 19 '19 at 06:08

2 Answers2

1

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

For example: 3 & 10 is 2.

 0011
&1010
 ----
 0010
druckermanly
  • 2,694
  • 15
  • 27
  • Thank you for the quick response. I guess the follow up question would be, when _in a real world situation_ would I ever need to produce a random number to manipulate its bits? I thought that when dealing with bits, you wanted precise control and not randomness. – Hawkbirdtree Oct 20 '19 at 01:35
  • Imagine you have a `enum Features {FOO = 1 << 0, BAR = 1 << 1, BAZ = 1 << 2, BANG = 1 << 3 };` and a `void DoThing(int feature_flags)` -- and you want to call `DoThing` with a random set of features. Then you'd be able to call `DoThing(rand() & 0xF)`, to get your feature. Either way, the compiler can't know what you're using the bits for. `rand()` returns a numeric type, not a "don't-use-me-for-bitwise-operations" numeric type. – druckermanly Oct 20 '19 at 03:03
1

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.

jkb
  • 2,376
  • 1
  • 9
  • 12