Variable declaration syntax
The meaning attributed to the phrase
“variable declaration” has historically been confusing and
contradictory, and it’s important that you understand the correct
definition so you can read code properly. A variable declaration tells the
compiler what a variable looks like. It says, “I know you haven’t
seen this name before, but I promise it exists someplace, and it’s a
variable of X type.”
In a function declaration, you give a
type (the return value), the function name, the argument list, and a semicolon.
That’s enough for the compiler to figure out that it’s a declaration
and what the function should look like. By inference, a variable declaration
might be a type followed by a name. For example:
int a;
could declare the variable a as an
integer, using the logic above. Here’s the conflict: there is enough
information in the code above for the compiler to create space for an integer
called a, and that’s what happens. To resolve this dilemma, a
keyword was necessary for C and C++ to say “This is only a declaration;
it’s defined elsewhere.” The keyword is
extern. It can mean the
definition is external to the file, or that the definition occurs later
in the file.
Declaring a variable without defining it
means using the extern keyword before a description of the variable, like
this:
extern int a;
extern can also apply to function
declarations. For func1( ), it looks like this:
extern int func1(int length, int width);
This statement is equivalent to the
previous func1( ) declarations. Since there is no function body, the
compiler must treat it as a function declaration rather than a function
definition. The extern keyword is thus superfluous and optional for
function declarations. It is probably unfortunate that the designers of C did
not require the use of extern for function declarations; it would have
been more consistent and less confusing (but would have required more typing,
which probably explains the decision).
Here are some more examples of
declarations:
//: C02:Declare.cpp
// Declaration & definition examples
extern int i; // Declaration without definition
extern float f(float); // Function declaration
float b; // Declaration & definition
float f(float a) { // Definition
return a + 1.0;
}
int i; // Definition
int h(int x) { // Declaration & definition
return x + 1;
}
int main() {
b = 1.0;
i = 2;
f(b);
h(i);
} ///:~
In the function declarations, the
argument identifiers are optional. In the definitions, they are required (the
identifiers are required only in C, not C++).