0

Output question in c

int i=10; void f(void){ int i=5;i=7; } void g() { i=9; } int main() { I=1; g(); f(); printf("%d", I); return 0; } Why is the output 9 here?

2nd Jan 2021, 3:50 PM
Achintya Raj
Achintya Raj - avatar
6 Answers
+ 9
In the f() function the variable i is declared again, making it a local variable, specific to the f() function only. Any changes within f() will not apply to the global version of i. Function g() however does not redeclare the variable i and therefore its changes apply to the global variable. Thus g() causes i = 9. But the function f() changes are do not apply to i. Hopefully that makes sense.
2nd Jan 2021, 3:59 PM
Elizabeth Kelly
Elizabeth Kelly - avatar
+ 2
Because i is originally declared as a global variable but is not const. Therefore i can be changed in any function, including those with a return type of void - just as long as it isn’t declared again as a local variable as it is in f().
2nd Jan 2021, 6:38 PM
Elizabeth Kelly
Elizabeth Kelly - avatar
0
int i=10; void f(void){ int i=5;i=7; } void g() { i=9; } int main() { i=1; g(); f(); printf("%d", i); return 0; } Why is the output 9 here?
2nd Jan 2021, 3:52 PM
Achintya Raj
Achintya Raj - avatar
0
But why not the answer should be 1
2nd Jan 2021, 4:50 PM
Achintya Raj
Achintya Raj - avatar
0
As other function are of void nature so changes remains unaffected
2nd Jan 2021, 4:52 PM
Achintya Raj
Achintya Raj - avatar
0
Ok thanks
2nd Jan 2021, 7:02 PM
Achintya Raj
Achintya Raj - avatar