919 views
2 2 votes

Study the following C programm code:

#include <stdio.h>
int main() {
    static char *p = (char *)malloc(10);
    return 0;
}

Which one of the following optiions is true for the above C Program code?

(A) Error: Lvalue required

(B) Error: Rvalue required

(C) Error: Invalid *p declaration

(D) No error

2 Answers

Best answer
3 3 votes

static data type variables are initialized at compile time.

Therefore the value to be assigned to static variable should be a compile time constant but malloc has been assaigned to static variable which allocates memory during runtime, so the compiler should throw an error saying "Rvalue required" for the static variable.

• edited by
0 0 votes

I have been searching for its correct answer for quite some time and here is what I found:-

The assumption that static data needs to be initialized by a constant expression everytime is not entirely accurate when it comes to C standards.

In C, static variables have static storage duration, which means they retain their value between function calls and are initialized only once. The initializer for a static variable must be a constant expression if the initialization happens at compile time. However, in the case of pointers, the address can be resolved at runtime.

The initialization of a static variable can indeed occur with the result of a runtime function, such as malloc, provided that it happens inside a function.

According to the C standard, static variables can be initialized with constant expressions or, in the case of pointers, with the result of a function call if the function call happens within a function.

However, some compilers enforce stricter rules and do not allow function calls in static initializers, as they expect static variables to be initialized at compile time, not runtime.

So, the answer is: (D) No error.

Position:
Show:

Related questions

0 0 votes
1 answers 1 answer
675
675 views
Debargha Mitra Roy asked Aug 3, 2024
675 views
Consider the code:#include <stdio.h int addsub(int, int); void display(int); void show(int, int); int main() { int i = 10, j = 20, k; k = addsub(i, j); printf("%d ", k); ...
1 1 vote
1 answers 1 answer
444
444 views
Debargha Mitra Roy asked Aug 3, 2024
444 views
Code:#include <stdio.h int abc() { printf("come"); } void main() { int abc(); abc(); (*abc)(); }When executes does - (A) results in compilation error(B) prints "comecome"...