Reputation: 69
I was trying to write a program that lists the factors of a given number. It works when I write this:
int main () {
int num, i;
printf("\nEnter a number: ");
scanf("%d", &num);
for(i == 0; i <= num; ++i) {
if (num % i == 0) {
printf("\n\t%d", i);
}
}
}
but not when the for loop is
for(i = 0; i <= num; ++i)
I'm confused as I thought this was the format of a for loop. Could someone point out my error please?
Upvotes: 0
Views: 222
Reputation: 643
The first part of the for loop is defining the starting value of your iterator (i
).
Since you are not initializing it, it could have an undefined value, or sometimes just garbage value...
So when you use i==0
you're not assigning the value to i
, just checking if it's equal to 0.
The value of i when not defined is usually very random, but it can have the integer max value, so incrementing it once actually makes it turn to the initger minimum value.
So actually the correct for is:
for(i=0; i<something; i++) // or ++i, doesn't mater
EDIT: oh yeah... and sinc the starting value of the for loop is 0, the something % i
is equal to something % 0
which means you're making a division by zero.
EDIT 2: i see it was already mentioned...
Upvotes: 0
Reputation: 370377
i == 0
is an expression with no side effects, so writing for(i == 0; i <= num; ++i)
is the same as writing for(; i <= num; ++i)
, i.e. it just does nothing in the initialization part. Now since you never initialize i
anywhere this means that you invoke undefined behaviour.
If you do i = 0
, i
is initialized, but you still invoke undefined behaviour: num % i
will cause division by zero because i
will be 0 at the beginning.
Now it happened that on your system the division by zero caused your program to crash, while the version where you used i uninitialized happened to run without crashing. That's why it may have appeared to you that the version using i==0
"worked".
Upvotes: 5
Reputation: 726839
In C there are two separate operators that look somewhat similar - an assignment statement which uses a single equal sign, and an equality comparison, which uses two equal signs. The two should not be confused (although very often they are).
i == 0
is a comparison with zero, not an assignment of zero. It is a valid expression, though, so the compiler does not complain: for
loop allows any kind of expression to be in its header, as long as the expression is formed correctly.
However, your code would not work, because it has undefined behavior: i
remains uninitialized throughout the loop, making your program invalid.
Upvotes: 2
Reputation: 691
You should start the loop in this case with i=1
as in for(i = 1; i <= num; ++i)
, otherwise you are trying to divide a number by 0
. Factor can never be 0
.
Upvotes: 8