user1190555
user1190555

Reputation: 59

Endless loop in C

Beginner here. Why is this an endless loop ?

for (p = 0; p < 5; p += 0.5)
{
    printf("p=%2.2f\n",p);
}

Upvotes: 3

Views: 333

Answers (5)

Timothy Kwok
Timothy Kwok

Reputation: 301

a type conversion problem, float/double lost precision when assigned to an integer type.

P.S. It is really a very bad idea to use float/double in condition test. Not all floating point numbers in computers are accurate.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You see an endless loop because your p is of an integral type (e.g. an int). No matter how many times you add 0.5 to an int, it would remain 0, because int truncates double/fp values assigned to it. In other words, it is equivalent to a loop where you add zero on each step.

If you make p a float or a double, your problem would go away.

EDIT (Suggested by Oli Charlesworth's comment)

It is worth noting that using floats and doubles to control loops is discouraged, because the results are not always as clean as in your example. Changing the step from 0.5 (which is 2 to the negative power of 1) to 0.1 (which is not an integral negative power of 2) would change the results that you see in a rather unexpected way.

If you need to iterate by a non-integer step, you should consider using this simple pattern:

// Loop is controlled by an integer counter
for (int i = 0 ; i != 10 ; i++) {
    // FP value is calculated by multiplying the counter by the intended step:
    double p = i * 0.5;
    // p is between 0 and 4.5, inclusive
}

Upvotes: 8

mikithskegg
mikithskegg

Reputation: 816

when you add a double constant to integer variable, the double constant "becomes" integer. 0.5 becomes just 0. So you add 0 to p.

Upvotes: 0

NPE
NPE

Reputation: 500357

If p is a float or a double, there's nothing wrong with the code, and the loop will terminate.

If p is integer, the behaviour of the code is undefined since the format specifier in printf() is wrong.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182639

I think it depends on how p is declared. If it's an integer type, p will always be 0 (because the result of 0 + 0.5 will be truncated to 0 every time) so the for will never stop.

Upvotes: 4

Related Questions