First question ever :)
I'm studying programming "by myself", reading "C Programming: A modern Approach" by K.N.King. In Chapter18 - Declarations, in the Q&A section, there is a question about why selection statements and iteration statements (and their "inner" statements) are considered to be blocks in C99. After a small introduction to the answer, he says:
[...]The C99 standard states that the object represented by a compund literal has static duration if the compound literal occurs outside the body of a function. Otherwise, it has automatic storage duration; as a result, the memory occupied by the object is deallocated at the end of the block in which the compound literal appears[...]
Which I think I understand. I've tried to return a pointer to a compound literal from a function, and indeed the output is wrong (or undefined I guess). My problem is the following; He gives this example:
/* Example 2 - if statements with braces */
double *coefficients, value;
if(x){
coefficients = (double[3]) {1.5, -3.0, 6.0};
}else{
coefficients = (double[3]) {4.5, 1.0, -3.5};
}
value = evaluate_polynomial(coefficients);
Followed by this explanation:
Each compound literal causes an object to be created, but that object exists only within the block formed by the braces that enclose the statement in which the literal appears. By the time
evaluate_polynomial
is called,coefficients
points to an object that no longer exist. The result: undefined behavior.
And when I try exactly that same code in my computer (I'm using GCC in a Linux VM), I always get the right output. The literal does not seem to be deallocated once the "control flow" exit the if
block.
Can someone elaborate a little more about this?
Thanks.
{1.5, -3.0, 6.0}
The literal must exist somewhere in the program, otherwise it cannot be assigned. So upon exiting the block,coefficients
points to the literal. – Whitenc++
but nothing relevant changed from C – Doppint a
was declared asstatic int a
, it wouldn't be a problem to return the address ofa
from the function. I was just afraid that the book is outdated and the storage duration of a literal created inside anif
block is static and not automatic, because I was not able to make the program fail. – Edict(double[3]){1.5, -3.0, 6.0}
should behave like a local variable and not like a string literal. – Pettigrew