Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C- while loop un-explained behaviour

I am trying to run the following code :

#include <sys/time.h>
#include <stdio.h>

int main()
{
unsigned int ms, oldms = 0,dif;
struct timeval tv;
while(1)
{
 gettimeofday(&tv, NULL);
 ms=tv.tv_sec; 
 //printf("%d\n",ms-oldms );
 dif=ms-oldms;
 if(dif>3)
   {    
        printf("3 seconds up");
        oldms=ms;
   }
 }
}

I am expecting it to print "3 seconds up" after every 3 seconds, but it doesn't display that message. I tried to debug it using gdb but nothing seems wrong and still no output. While trying to debug, I added a printf statement and magically the output can be seen.

If I run the program after removing the //printf("%d\n",ms-oldms ); statement , there is no output again.I am not sure what's happening and whether its dependant on anything.

$gcc --version gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2

like image 897
kid Avatar asked Dec 16 '15 12:12

kid


People also ask

Do while loop in C explained?

do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again.

How do you explain a while loop?

A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".

What is do while loop short answer?

In most computer programming languages, a do while loop is a control flow statement that executes a block of code at least once, and then either repeatedly executes the block, or stops executing it, depending on a given boolean condition at the end of the block.

What is a do while loop demonstrate with an example?

The do while loop is an exit controlled loop, where even if the test condition is false, the loop body will be executed at least once. An example of such a scenario would be when you want to exit your program depending on the user input.


1 Answers

Output buffering is the reason.

stdout is line buffered by default when attached to a terminal device. You can flush this out using fflush(stdout); or using \n in printf() i.e. printf("3 seconds up\n");. or disabling it with setbuf(stdout, 0);

I/O is slow in general. So implementations use a fixed size buffer and printf once it gets full. In practice, calling fflush(stdout); too often can affect performance.

like image 79
P.P Avatar answered Oct 06 '22 03:10

P.P