4

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?

Caleb Waggoner
  • 147
  • 1
  • 2
  • 13
  • 1
    I don't know the answer to your question but I would recommend you create a function like: POINT createPOINT(x,y) to init all your POINT type vars. – El Developer Oct 09 '11 at 01:38

3 Answers3

6

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.

Omri Barel
  • 9,182
  • 3
  • 29
  • 22
2

The problem is that C isn't an Object language and only does strict typing. Further, C maintains a difference between structs and arrays.

The way your code will have to work is

void foo( short x, short y )
{
 POINT here; 
 here.x = x;
 here.y = y;
}
Mark Robinson
  • 3,135
  • 1
  • 22
  • 37
  • I know that's a fix for it, I was more wondering why Watcom's compiler throws the error when others (gcc and MSVC to be specific) do not... Do you suppose that Watcom still operate on pre-C89 standards? – Caleb Waggoner Oct 09 '11 at 01:45
  • That's entirely possible. Not all compilers meet the spec entirely. – Mark Robinson Oct 09 '11 at 01:46
  • GCC by default does not strictly compile against C89 unless you specify `-ansi` or `std=c89`. By default it is C89 with certain C99 features. Arguably you should always compile against a standard with GCC for portability. – Andrew Marshall Oct 09 '11 at 01:49
0

This is normal for C89... initializers do need to be constant, ie. able to be determined at compile time. This means no variables in initializers, and it's true for other types as well, not just structs. In C99, your code would work.

Dmitri
  • 9,175
  • 2
  • 27
  • 34