Case 1:Error:initializer element is not constant
static char *p =(char*)malloc(10);
Case 2:
static char *p ;
p= (char*)malloc(10);
Any idea why i am getting error in case 1 and why not in case 2
Case 1 is an initialization; case 2 is an assignment.
Roughly speaking, initialization happens when a variable is
created. Creation of `static' variables occurs before any program
code executes, so the initializer's value must be obtainable without
running any executable code. That's why you can't initialize a
`static' variable with the value of a function: You'd have to call
the function and execute its body, and you can't execute code before
code executes.[*]
The lines of case 2 are inside a function (if they were not, the
compiler would have complained). As in case 1 the `static' variable
is created before the program starts, and since no explicit initializer
is given the variable is initialized with "the right kind of zero," in
this case a NULL. That's a constant value, which can be calculated
without running any code, so all is well. When your program starts
running, it (presumably) calls the function containing these lines,
and then the assignment calls the malloc() function to get a value.
Calling functions once the program is running is perfectly all right,
as is assigning their values to variables.
Incidentally, the `(char*)' casts are unnecessary.
[*] Some C-related languages allow initialization to execute
code, but this is by no means a straightforward matter; it is fraught
with complication. For example, consider the apparently simple
int f(void), g(void);
static int fvalue = f();
static int gvalue = g();
Seems easy? Well, what if
int f(void) { return gvalue + 1; }
int g(void) { return fvalue + 2; }
? The outcome now depends on whether f() or g() executes first, and
whichever it is will "see" the other's variable in an incompletely
initialized state. Languages that permit this sort of thing have
(and need) dauntingly complex rules to determine what happens; C
loses some power by forbidding such initializations, but manages to
do without the considerable baggage of all those rules.