Thread: My program's in an infinite loop!

1. My program's in an infinite loop!

My program is designed to run an input value into 'mux', shift some bits around and such, using bitwise operations, and then give me an output value. It will then print off a line with some values.

The problem is, when I run the program, it's stuck in an infinite loop which always prints the following:
Code:
`Input = 0, S = 15, Y = 0`
So please, if you could tell me where I went wrong and what I could do to fix this problem, I'd be quite grateful
Thanks

I've included my code below:

Code:
```#include <stdio.h>
#include <stdlib.h>

void mux(input, selector) {
int output;

if (selector == 255) {
int input2;
input2 = input >> 4;
input = input | input2;  /*line 10*/
}

output = input & 15;
printf ("Input = %d, S = %d, Y = %d \n", input, selector, output);
}

main() {
int input, i;
int selector;  /*line 20*/

printf("Testing input line A, B = 0 \n");
for (i=0; i<=15; i++) {
selector = 15;
input = i;
mux(input, selector);
}
printf("\n");

printf("Testing input line A, B = 15 \n");  /*line 30*/
for (i=240; i<=255; i++) {
selector = 255;
input = i;
mux(input, selector);
}
printf("\n");

printf("Testing input line B, A = 0 \n");
for (i=0; i<=240; i+16) {
if (i <= 15) {
selector = 15;  /*line 40*/
}
else {
selector = 255;
}
input = i;
mux(input, selector);
}
printf("\n");

printf("Testing input line B, A = 15 \n");
for (i=15; i<=255; i+16) {  /*line 50*/
if (i <= 15) {
selector = 15;
}
else {
selector = 255;
}
input = i;
mux(input, selector);
}
printf("\n");
} /* line 60*/```

2. Code:
`for (i=0; i<=240; i+16) {`
should be:
Code:
`for (i=0; i<=240; i+=16) {`
You made the same mistake for the next loop.

3. Ah, wow, thanks! I would've -never- though to look at those loops to be honest, but now my program runs how it should Thanks again!

4. Infinite loops:

When a program performs as an infinite loop, there are two places one should look.

The first place should be the loop exit condition. If it is always true and there are no other loop exit control statements as break, or goto statements then the loop will go forever!

The second place is the loop control variables, with the most common mistake that they are either not updated with every loop iteration, or their update does not evaluate to a false loop exit condition (a bit more tricky to spot...).

Always check those two locations when facing the dreaded infinite loop!