Home > Mobile >  How can I write variable definition without declaration?
How can I write variable definition without declaration?

Time:10-11

I can write declaration or declaration with definition. Examples:

int x = 1; // declaration and definition
extern int x; // only declaration
bool f(); // only declaration
bool g() {} // declaration and definition
class X; // declaration
class X {}; // declaration and definition

So we can see that this is possible to write only declaration and declaration with definition. But how I can write only definition? I heard that this is possible.

CodePudding user response:

There is no definition without a declaration, since the meaning of the first term includes the second. Further, I provided some information from the C drafts (6.2. Declarations and definitions):

A declaration is said to be a definition of each entity that it defines.

Link: https://eel.is/c draft/basic.def

CodePudding user response:

You cannot write a definition for something that is undeclared, point blank. But you do have C constructs for writing definitions that may not serve as a first declaration. Here they are:

struct C {
    static int i;
};

int C::i = 1;

namespace N {
    extern int i;
}

int N::i = 2;

Neither int C::i = 1; nor int N::i = 2; may serve as an initial declaration for i. Those definitions are invalid unless a previous declaration of each respective i is present. So in a way they are non-declaring definitions.

This answer may be contentious, and possibly not fall under the answers you had in mind, but those would be the examples.

  • Related