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;
}
  1. A. Function parameters cannot be copied into static variables in any way
  2. B. A static local must be initialised with a constant expression, because it is initialised before the program starts
  3. C. A static variable cannot be declared inside a function
  4. 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

Exams that ask this topic