Predict the output of the below programs.
Question 1
int main() { int c=5; printf("%d\n%d\n%d", c, c <<= 2, c >>= 2); getchar(); } |
Output: Compiler dependent
Evaluation order of parameters is not defined by C standard and is dependent on compiler implementation. It is never safe to depend on the order of parameter evaluation. For example, a function call like above may very well behave differently from one compiler to another.
References:
http://gcc.gnu.org/onlinedocs/gcc/Non_002dbugs.html
Question 2
int main() { char arr[] = {1, 2, 3}; char *p = arr; if(&p; == &arr;) printf("Same"); else printf("Not same"); getchar(); } |
Output: Not Same
&arr is an alias for &arr[0] and returns the address of the first element in array, but &p returns the address of pointer p.
Now try below program
int main() { char arr[] = {1, 2, 3}; char *p = arr; if(p == &arr;) printf("Same"); else printf("Not same"); getchar(); } |
Question 3
int main() { char arr[] = {1, 2, 3}; char *p = arr; printf(" %d ", sizeof(p)); printf(" %d ", sizeof(arr)); getchar(); } |
Output 4 3
sizeof(arr) returns the amount of memory used by all elements in array
and sizeof(p) returns the amount of memory used by the pointer variable itself.
Question 4
int x = 0; int f() { return x; } int g() { int x = 1; return f(); } int main() { printf("%d", g()); printf("\n"); getchar(); } |
Output: 0
In C, variables are always statically (or lexically) scoped. Binding of x inside f() to global variable x is defined at compile time and not dependent on who is calling it. Hence, output for the above program will be 0.
On a side note, Perl supports both dynamic ans static scoping. Perl’s keyword “my” defines a statically scoped local variable, while the keyword “local” defines dynamically scoped local variable. So in Perl, similar (see below) program will print 1.
$x = 0; sub f { return $x; } sub g { local $x = 1; return f(); } print g()."\n"; |
Reference:
http://en.wikipedia.org/wiki/Scope_%28programming%29
Please write comments if you find any of the above answers/explanations incorrect.
Recommended Posts:
- Output of C Programs | Set 1
- Output of C Programs | Set 2
- Output of C Programs | Set 3
- Output of C Programs | Set 4
- Output of C Programs | Set 5
- Output of C Programs | Set 6
- Output of C Programs | Set 7
- Output of C Programs | Set 11
- Output of C Programs | Set 12
- Output of C Programs | Set 14
- Output of C Programs | Set 13
- Output of C Programs | Set 16
- Output of C++ programs | Set 50
- Output of C programs | Set 29
- Output of Java Programs | Set 12
- Output of Java programs | Set 10 (Garbage Collection)
- Output of C++ programs | Set 21
- Output of Java programs | Set 13 (Collections)
- Output of C programs | Set 30 (Switch Case)
- Output of C++ programs | Set 22

