ProgrammingHardProduct company OA · GATE CS
Why does this fail to compile in C?
Why does this fail to compile in C?
void f(int n) {
static int k = n;
}- A. Function parameters cannot be copied into static variables in any way
- B. A static local must be initialised with a constant expression, because it is initialised before the program starts
- C. A static variable cannot be declared inside a function
- D. k must be declared const because it is static
Correct answer: B. A static local must be initialised with a constant expression, because it is initialised before the program starts
Objects with static storage duration are initialised once, before main runs, so their initialisers must be constant expressions. Writing static int k; k = n; would compile, because that is an assignment at run time, not an initialisation.
More C Programming questions
- Which line correctly allocates space for a copy of a string pointed to by const char s?
- What is printed? c int a = 3, b = 0; int r = (a > b) + (a && b) 2 + (a || b) 4 + !b 8; printf("%d", r);
- What is printed? c int a[] = {5, 1, 4, 2, 3}; int lo = a, hi = a + 4; while (lo < hi) { if (lo > hi) lo++; else hi--; } printf("%td %d"…
- What is printed? c long memo[50]; int calls = 0; long f(int n) { calls++; if (n < 2) return n; if (memo[n]) return memo[n]; return memo[n]…
- With 4-byte int, what is printed? c int x = 7; printf("%zu %zu", sizeof (int) 3, sizeof x + 1);
- What is printed? c char s[8] = {'a', 'b'}; printf("%zu %zu %d", strlen(s), sizeof s, s[7]);