A declaration establishes the names and characteristics of data objects and functions used in a program. A definition allocates storage for data objects or specifies the body for a function. When you define a type, no storage is allocated.
Declarations determine the following properties of data objects and their identifiers:
The declaration for a data object can include the following components:
One of the fundamental differences between C++ and C
is the placement of variable declarations. Although variables are
declared in the same way, in C++, variable declarations can be
put anywhere in the program. In C, declarations must come before
any statements in a block. In the following C++ example, the
variable d is declared in the middle of the main() function:
#include <iostream.h> void main() { int a, b; cout << "Please enter two integers" << endl; cin >> a >> b; int d = a + b; cout << "Here is the sum of your two integers:" << d << endl; }
A given function, object, or type can have only one definition. It can have more than one declaration as long as all of the declarations match. If a function is never called and its address is never taken, then you do not have to define it. If an object is declared but never used, or is only used as the operand of sizeof, you do not have to define it. You can declare a given class or enumerator more than once.
The following table shows examples of declarations and definitions. The identifiers declared in the first column do not allocate storage; they refer to a corresponding definition. In the case of a function, the corresponding definition is the code or body of the function. The identifiers declared in the second column allocate storage; they are both declarations and definitions.
Declarations | Declarations and Definitions |
---|---|
extern double pi; | double pi = 3.14159265; |
float square(float x); | float square(float x) { return x*x; } |
struct payroll; | struct payroll { char *name; float salary; } employee; |
Program Linkage between
Identifiers
Scope of Identifier
Visibility
Storage Duration
Block Scope Data
Declarations
File Scope Data
Declarations
Declarators
Storage Class
Specifiers
Initializers
Type Specifiers
Declaring and
Using Bit Fields
Declaring a
Packed Structure
Defining a
Packed Union
Declarators
Initializers
Syntax of a
Data Declaration
Type
Specifiers