Skip to content

Instantly share code, notes, and snippets.

@BaSmi
Last active January 4, 2016 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BaSmi/8539238 to your computer and use it in GitHub Desktop.
Save BaSmi/8539238 to your computer and use it in GitHub Desktop.
For loop ends one step later than expected
#include <cs50.h>
#include <stdio.h>
int main (void)
{
bool parm = false;
int i = 0;
for (i = 0; i < 7 && !parm; i++)
{
printf("loop: %d\n", i);
if (i == 4)
{
parm = true;
}
}
printf("end: %d\n", i);
}
@BaSmi
Copy link
Author

BaSmi commented Jan 21, 2014

The last time line 11 prints to the screen i = 4. But When line 18 prints i = 5. I would have expected 4 again. If I break after line 14, I end with i = 4. Can somebody help me understand why this loop behaves the way it does?

@IncipientLT
Copy link

It is because it finished that cycle of the for loop after i was already 4, thus it iterated i. It then found that the "!parm" condition was no longer met, then broke out of the loop.

If you wanted to break out of the loop as soon as i == 4, you should use a break statement, "break;" to exit out of the for loop. Place "break;" on the next line after "parm = true;" to see the results.

@BaSmi
Copy link
Author

BaSmi commented Jan 21, 2014

Thanks! I wrongly assumed i++ would only happen after evaluating the condition.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment