edited by
843 views
1 votes
1 votes

I have learnt that order of function call of f1() and f2() is compiler dependent from K&R book.Why precedence and associavity does not work in this case ?? Please clarify in details .
 

#include<stdio.h>
int x = 0;
int f1() {
x = 5;
return x;
}
int f2() {
x = 10;
return x;
}
int main() {
int p = f1() + f2();
printf("%d ", x);
return 0;
}
edited by

1 Answer

Best answer
4 votes
4 votes
  • #include<stdio.h>
    int x = 0;
    int f1() {
    x = 5;
    return x;
    }
    int f2() {
    x = 10;
    return x;
    }
    int main() {
    int p = f1() + f2();
    printf("%d ", x);
    return 0;
    }
  • #include<stdio.h>
    int x = 0;
    int f1() {
    x = 5;
    return x;
    }
    int f2() {
    x = 10;
    return x;
    }
    int main() {
    int p = f2() + f1();
    printf("%d ", x);
    return 0;
    }


This is a case of Unspecified Behaviour (Or preferably Compiler Dependent).

Because, Your compiler has the freedom to run the either function $f1$ or $f2$ first . So, your compiler has alternatives to run which one first and it can go with anyone .

Unspecified behaviour comes when your vendor has no idea what compiler will do, hence he/she cannot document that this particular behaviour happens. As, compiler picks any one of the provided alternatives henceforth the name comes Unspecified behaviour .


NOTE :- If you remember race condition from OS

That which thread executes last, will change the output and intermediate threads which run have lost their updates. Same concept is being followed here . Also, note the difference between Unspecified Behaviour and Undefined Behaviour .

selected by

Related questions

1 votes
1 votes
0 answers
1
Mahbub Alam asked Nov 15, 2018
550 views
what is the result of comparing signed with unsigned number??#include <stdio.h>int main(){ unsigned int a = 5;if(a -1)printf("5 is -1\n"); return 0; }
1 votes
1 votes
1 answer
2
1 votes
1 votes
1 answer
3
aaru14 asked Oct 11, 2017
236 views
i=0;j= i ;printf( i++ + i + i + j + i + i);the output??