+ 1

Why is the output 1 2 4 3?

#include <stdio.h> int glob; int eflat(int n) { glob=glob+1; return glob; } int main(void) { glob=0; printf("%d ",eflat(0)); printf("%d\n",eflat(0)); printf("%d %d\n", eflat(0),eflat(0)); return 0; } I don't understand why when I call the function in the same printf the output is 4 3. I won't supposed to be 3 4?

14th Apr 2020, 3:13 PM
Cristian Daraban
Cristian Daraban - avatar
2 odpowiedzi
+ 3
For this you need to know the concept of stack. A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. Now coming to your question: After executing printf ("%d", eflat(0)); printf ("%d", eflat(0)); we know the value of glob is 2. the confusion is with this line. printf("%d %d", eflat(0), eflat(0)); | eflat(0) |=> glob = glob + 1 = 3 + 1 = (4) -------------- | eflat(0) |=> glob = glob + 1 = 2 + 1 = (3) -------------- | main() | -------------- Looking at the diagram above we are sure using stack of dealing with data (4) will come first or pop and printed and then (3) will be printed this is the reason why output is 1 2 4 3
14th Apr 2020, 4:04 PM
minirkk
minirkk - avatar
+ 2
Test on C4Droid and rextester.com (C - clang) outputs 1 2 3 4 Looks like compiler specifics (gcc).
14th Apr 2020, 4:28 PM
Ipang