1

If a statement inside it depends on the same variable as if it depends on

 3 years ago
source link: https://www.codesd.com/item/if-a-statement-inside-it-depends-on-the-same-variable-as-if-it-depends-on.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

If a statement inside it depends on the same variable as if it depends on

advertisements

consider the below programs. I would like to know why this codes behave in different way.Thankyou in advance.

this doesnot print any

#include <stdio.h>

int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d", i++);
    }
}

while this does

#include <stdio.h>
int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d\n", i++);
    }
}


First note both your programs never exit. When i hits 7 it's game over and your stuck forever doing nothing.

Second note the only difference is printing a new line. That should have been your clue. Since the loop is infinite you never print a new line or exit - both things flush STDOUT. Until you flush STDOUT you're just accumulating what you're trying to print in a buffer. Only the flushing will get it on screen, and clean the buffer.

@chux added a good point:

Buffering of STDOUT (or IN or ERR) is implementation defined, meaning different flavors of Linux, Windows, and so forth may display different behavior. Obviously in the OP STDOUT is buffered - as no output appears.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK