On 27 Nov 2009, at 13:30, Jeremy Pereira wrote:

> You can't have non constant elements in struct initialisers, testy is not a 
> constant.  The error message spells out exactly what the issue is.

You *can* have non-constant elements in struct initialisers in C, *but* only in 
a context where there is code that will execute at runtime.

So

  struct foo {
    int foo;
  };

  int fn (int anInt) {
    struct foo fooArray[] = { { anInt }, { anInt + 1 } };
  }

is quite legitimate, while as you rightly point out

  extern int anInt;

  struct foo {
    int foo;
  }

  struct foo fooArray[] = { { anInt }, { anInt + 1 } };

isn't.

In the case of C89/C90, this is an extension provided by GNU C and by some 
other compilers.  It's a formal part of C99, however (see §6.7.8 ¶4 - "All the 
expressions in an initializer for an object that has static storage duration 
shall be constant expressions or string literals.").

In C++, however, the standard says that it's allowed wherever, including for 
objects that have static storage (see §8.5 ¶2), so in C++, both of those pieces 
of code should compile.  There are some caveats, however, in that the order of 
initialisation of objects is not specified; the standard does guarantee that, 
if they haven't yet been initialised dynamically, they'll have been temporarily 
initialised to zeroes (§8.5 ¶6).  Given that there are additionally some issues 
surrounding the implementation of this feature (e.g. it may be necessary to 
call a special function to perform these initialisations on some platforms if 
the module in question doesn't have a conventional main() function, for 
whatever reason), it's probably best to avoid relying on this ability.

Kind regards,

Alastair.

-- 
http://alastairs-place.net



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to