Q
Q
Qubc2020-11-13 21:05:37
C++ / C#
Qubc, 2020-11-13 21:05:37

Why is it possible to declare a global variable of a struct type before declaring that struct type?

struct interval b;

struct interval 
{
  int first;
  int second;
};

int main ()
{

}


But:
int main ()
{
  struct interval b; error: storage size of 'b' isn't known
 	struct interval 
  {
    int first;
    int second;
  };
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-11-13
@Qubc

Why is it possible to declare a global variable

Because the declaration only says that the name exists and has such and such a type. It does not cause memory allocation or any other actions for which you need to know how the type associated with the identifier works.
In your second example , it's a variable definition that allocates stack space for it. But it can be rewritten to make b a declaration too, like so:struct interval b
int main ()
{
  extern struct interval b;
  struct interval 
  {
    int first;
    int second;
  };
}

Going back to the first example, this is a tentative definition with an external link. The standard (C99) says the following about it (6.9.2:2):struct interval b;
A declaration of an identifier for an object that has file scope without an initializer,
and without a storage-class specifier or with the storage-class specifier static, constitutes
a tentative definition. If a translation unit contains one or more tentative definitions for
an identifier, and the translation unit contains no external definition for that identifier,
then the behavior is exactly as if the translation unit contains a file scope declaration of
that identifier, with the composite type as of the end of the translation unit, with an
initializer equal to 0.

The most important thing here is as of the end of the translation unit, i.e. the type of the object from the tentative definition must still be determined, but not before the appearance of this tentative definition, but before the end of the translation unit (or earlier, if the definition with the initialization of this object suddenly occurs).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question