Dims
Dims

Reputation: 51029

Can one declare but not define local variable in C/C++?

Sorry, forgot, was it possible to declare but not define local (inside function) variable in C/C++?

Looks like it is not possible, since it is impossible to access local variable from somewhere else, except this function.

Then, what is it correct to say: variable should be "declared" before use or "defined" before use?

Upvotes: 3

Views: 1005

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254461

Sorry, forgot, was it possible to declare but not define local (inside function) variable in C/C++?

No, local (block-scope) variables only have declarations. They are instantiated when the program reaches the declaration, with no need for a separate definition to control instantiation.

Then, what is it correct to say: variable should be "declared" before use or "defined" before use?

Variables, and named entities in general, must be declared before use. Not all variables have separate definitions; if they do, then the definition doesn't usually need to be available to use the variable.

Global (namespace-scope) and static member variables (depending on use) need definitions, to determine which translation unit is responsible for instantiating them. Global variables can also be declared separately from their definition, in their namespace or in functions inside that namespace.

Upvotes: 3

Gyapti Jain
Gyapti Jain

Reputation: 4106

For local variables, there is no concept of definition. They are just declared and are conditionally instantiated according to the flow of program.

Separate declaration and definition are used for global variables and functions.

Upvotes: 1

Related Questions