0
#include <stdio.h>
#include <conio.h>

int main(void)
{
    char ch;
    for(ch=getche(); ch!='q'; ch=getche());
    printf("Found the q");
    return 0;
}

I can't understand how the for loop here works . I can understand the initialization and the conditional test . But don't get why I have to use getche function again in increment portions .

3 Answers3

4

It may help to rewrite this for loop into an equivalent while loop:

for(ch=getche(); ch!='q'; ch=getche());

becomes

ch = getche();
while (ch != 'q') {
    ch = getche();
}

So you repeatedly get a new character by calling getche, until the character you get is equal to 'q'.

Without the second ch=getche(), you would get only a single character and compare this to 'q' over and over again (leading to an infinite loop if it isn't 'q').

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
1

Remember how a for loop typically works:

for ( init-expressionopt ; test-expressionopt ; update-expressionopt )
  statement

init-expression (if present) is evaluated exactly once; it (typically) sets up the thing we’re testing against. In this case, it initializes the value the of ch by calling getche.

Before each loop iteration, test-expression (if present) is evaluated; if zero, the loop exits. In this case, the test is ch != 'q'.

After each loop iteration, update-expression (if present) is evaluated; it updates the thing we’re testing against. In this case, it updates the value of ch by executing another getche call. Without this step, the value of ch would not change and the loop would execute indefinitely.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

To make it clear rewrite the for loop:

for(ch=getche(); ch!='q'; ch=getche());

the following way:

for(ch=getche(); ch!='q'; )
{
    ch=getche();
}

That is the statement in the body of the second for loop:

ch=getche();

is moved as an expression in the third part of the first for loop.

In the third part of for loop there may be used any expression not only an expression with the increment or decrement operator.

halfer
  • 19,824
  • 17
  • 99
  • 186
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335