3

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?

Dims
  • 47,675
  • 117
  • 331
  • 600
  • 2
    you can do an `extern` declaration inside a function, but that will not be bound to that functions scope – sp2danny Mar 02 '15 at 13:45
  • 1
    Related/duplicate: [What is the difference between a definition and a declaration?](http://stackoverflow.com/q/1410563/256138) – rubenvb Mar 02 '15 at 13:46
  • Yes, I remember this, `extern` will be global. What about "normal" variables, i.e. ones we talking about, when starting to learn programming? – Dims Mar 02 '15 at 13:46
  • @rubenvb answers do not touch local variables; Michael's answer has an example of "definition" without any word about declaration (of local variables) – Dims Mar 02 '15 at 13:48
  • @Dims that's why I didn't close your question as a duplicate. Your question is somewhat academic though. Is there anything specific you are trying to accomplish? – rubenvb Mar 02 '15 at 13:54

2 Answers2

3

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

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.

Gyapti Jain
  • 4,056
  • 20
  • 40