Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C structure initialization with variable

I've run into a problem that seems to not be addressed by any of the C Standards after C89 save for the mention that structures initialization limits had been lifted. However, I've run into an error using the Open Watcom IDE (for debugging) where the compiler states that the initializer must be a constant expression.

Here's the gist of what's going on.

typedef struct{
 short x;
 short y;

} POINT;

void foo( short x, short y )
{
 POINT here = { x, y }; /* <-- This is generating the error for the compiler */

 /* ... */

}

Any ideas why, or what standard disallows that?

like image 977
Caleb Waggoner Avatar asked Feb 23 '23 18:02

Caleb Waggoner


1 Answers

The following quote is from the C99 rationale:

The C89 Committee considered proposals for permitting automatic aggregate initializers to consist of a brace-enclosed series of arbitrary execution-time expressions, instead of just those usable for a translation-time static initializer. Rather than determine a set of rules which would avoid pathological cases and yet not seem too arbitrary, the C89 Committee elected to permit only static initializers. This was reconsidered and execution-time expressions are valid in C99.

like image 198
Omri Barel Avatar answered Mar 03 '23 21:03

Omri Barel