0

The following code is similar to that of question Is there a difference between initializing a variable and assigning it a value immediately after declaration? downvoted twice, so I am at risk ;-)

short i; 
i = 2;

It does not compile with MinGW and -std=c99 -- why? The first line is a declaration of identifier i, not a definition of an object. However, the identifier has file scope and thus external linkage by default. It may be declared and defined elsewhere. The second line could be an assignment to that object. But gcc complains about a missing type or storage class and --after guessing the type as int-- about a type conflict.

Community
  • 1
  • 1
Rainald62
  • 706
  • 12
  • 19

1 Answers1

1

You say that short i; has file scope, which implies to me that it (edit: and the subsequent i = 2;) is outside a function. Outside a function, i = 2; on its own is complete nonsense; as a statement, it cannot appear outside a function. (edit) As statements cannot appear outside functions, the "assignment" must be a definition. In old C code, a definition without a storage class was an int definition, so your code is equivalent (under those rules, which it looks like GCC is applying) to:

short i;
int i = 2;

which of course is complete nonsense to a C compiler. (end edit)

You can get more-or-less the effect you're after by defining and initializing:

short i = 2;

This does not work if you merely wish to declare an external variable; in that case, put the initialization in the file with the definition, or in one of your functions (as below).

extern short i;
int main(int argc, char **argv) { i = 2; /* more code */ }
  • Thanks for "... complete nonsense". So gcc has no alternative way to interprete it. Besides, am I right that "extern" isn't needed in your code as it is the default? I refer to C99 section 6.2.2 clause 5 but most answers to stackoverflow.com/questions/1410563 are opposing. – Rainald62 Apr 26 '13 at 01:58
  • `extern short i;` is a declaration. `short i;` is a definition as well. If `i` is defined somewhere else you don't want to define it yourself. – michaelb958--GoFundMonica Apr 26 '13 at 02:03
  • Do you know the section of the standard treating definition? If not, what is the meaning of definition in terms of behaviour of the abstract machine? – Rainald62 Apr 26 '13 at 09:41
  • Found it. Section 6.9.2. Learned of "tentative definitions". – Rainald62 Apr 26 '13 at 10:59
  • `i = 2;` at file scope is not nonsense. The compiler is operating in a mode in which it accepts old C syntax. In this syntax, `i = 2;` is a definition of `i` with default type `int`. This conflicts with the previous declaration of `i` as `short`, which is why the compiler complains of conflicting types. – Eric Postpischil Apr 26 '13 at 11:12
  • @EricPostpischil I didn't actually know that. I'll edit it in. – michaelb958--GoFundMonica Apr 27 '13 at 02:06