why system function execute first

Viewed 83

the problem is when i run this code the system function start first and as per my understanding (which is very little), printf function should start first then the system function !

#include<stdio.h>
#include<stdlib.h>

int main()
{
    printf("test1");
    system("echo 'test2'");
}

and it output :

test2
test1

but the output should be like this instead!

test1
test2
2 Answers

You have to add a line break (\n) to the printf statement. I can only give you my basic (probably not entirely correct) explanation. printf gives the characters to a buffer for printing to the console. This buffer is then printed per line. If you add the \n the line is printed instantly.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    printf("test1\n");
    system("echo 'test2'");
}

i just find the explination its when we say printf is actually what we call buffered the output that we ask to print to standard out in this case our display doesn't come to the display immediately it goes into a holding pool a buffer and when that buffer gets filled up it'll dump everything out at once it's an efficiency consideration but if we print out a new line that \n it will go ahead and it will flush the buffer out right ,so to fix it we can use :

#include<stdio.h>
#include<stdlib.h>
int main()
{

printf("test1\n");
system("echo 'test2'");
}

or :

#include<stdio.h>
#include<stdlib.h>

int main()
{

printf("test1");
fflush(stdout);
system("echo 'test2'");
}

both do the same job (flush the output buffer).

Related