What is the output of this C code?
#include <stdio.h> int main() { int x = 5; { int x = 10; printf("%d\n", x); } printf("%d\n", x); return 0; }
Remember that inner blocks can have variables with the same name that hide outer ones.
The inner block declares a new variable x with value 10, which shadows the outer x. So inside the block, x is 10. Outside, it remains 5.
What will be printed when this program runs?
#include <stdio.h> void counter() { static int count = 0; count++; printf("%d ", count); } int main() { counter(); counter(); counter(); return 0; }
Static variables inside functions keep their value between calls.
The static variable count is initialized once to 0, then incremented each call. So outputs are 1, then 2, then 3.
What is the output of this program?
#include <stdio.h> int val = 100; void printVal() { int val = 50; printf("%d ", val); } int main() { printVal(); printf("%d\n", val); return 0; }
Local variables hide global variables inside their scope.
The function printVal has a local val set to 50, so it prints 50. The global val remains 100, printed in main.
What will this program print?
#include <stdio.h> int main() { int x; printf("%d\n", x); return 0; }
Local variables are not automatically set to zero.
The local variable x is uninitialized and contains garbage data. Printing it shows an unpredictable value.
Given these two files, what is the output when compiled and run together?
file1.c
#includestatic int count = 5; void printCount() { printf("%d\n", count); }
file2.c
#includeextern int count; int main() { printCount(); printf("%d\n", count); return 0; }
Static variables have internal linkage and are not visible outside their file.
The count variable in file1.c is static, so it cannot be linked from file2.c. The call to printCount() works and prints 5, but the extern int count; in file2.c causes a linker error because count is not found.