I'm reading PPP and trying to understand the difference between declaration, definition, and initialization. Is there a statement that only declares a variable?
Can I declare a variable in C++ without defining it?
Answers
Yes. extern int x; declares x as an int without defining it or initializing it. It tells the compiler that the variable exists, but its definition must be provided elsewhere if the program uses it in a way that requires one.
For comparison, int x; is a definition as well as a declaration. Adding an initializer, as in int x = 5;, initializes the variable too.
Reply to this answer
Declaration-only syntax isn't limited to variables. double func(double a, double b); declares a function, and class A; declares a class without defining it. Those are different kinds of entity, but they show the same general distinction between introducing a name and providing its definition.
Reply to this answer
The compiler and linker handle different parts of this. A declaration can give the compiler enough information to check a use, but if the program needs a definition and none is supplied, you can get a linker error. Just declaring a variable doesn't itself guarantee that storage has been defined for it.
Reply to this answer
Add your answer
Answers are reviewed before publication.
cobalt_umbrella:
One wrinkle: extern int x = 5; is a definition because it has an initializer. The declaration-only example is the one without an initializer.