I am working on a very small program to find the divisors of an integer in C++. My main method pretty much cins an int to a var and calls the factor method with the int as the argument. Here's the code:
void factor(int num)
{
for(int x = 0; x < ((num + 2) / 2); x++)
{
if((num % x) == 0)
{
cout << x << " ";
}
}
}
The program always crashes inside factor(). If I use this code, it runs fine:
void factor(int num)
{
for(int x = 0; x < ((num + 2) / 2); x++)
{
{
cout << x << " ";
}
}
}
So the problem is somewhere in the if((num % x) == 0)
. When I change that line to if((num % 2) == 0)
or if((num % 5) == 0)
, it produces the right results (I'm using 32 as the test input).
I learned C++ a few years ago and forgot most of it, after running into this issue I copied the code word for word off of my previous solution to this problem (which worked). But the program still crashes whenever I try to access the loop counter.
I'm using Code::Blocks 13.12 with GCC "4.9.0 20140604 (prerelease)" on Arch Linux 64-bit.
The problem is that you have an division-by-zero in your first snippet, something which is undefined-behavior according to the standard (n3337):
5.6p4
Multiplicative operators[expr.mul]
The binary
/
operator yields the quotient, and the binary%
operator yeilds the remainder from the division of the first expression by the second. If the second operand of/
or%
is zero the behavior is undefined.
Since the program cannot calculate the value of such expression it will crash.
if((num % x) == 0) // num % 0 on first iteration, application will crash, or order pizza
{
cout << x << " ";
}