- Variable Declaration
- A variable declaration is when you specify a type and an identifier, but have not yet assigned a value to the variable.
- Variable Definition
- A variable definition is when you assign a value to a variable, typically with the assignment operator =.
In the C programming language, variables must be declared before they can be used. This tells the compiler how to work with the variable and tells the linker how much space needs to be allocated for it.
Variable Declarations
To declare a variable, you need to provide its type and an identifier (name). The general form for declaring variables is:
type identifier1, identifier2, … identifiern;
This means you can declare one or more variables of the same type by starting with the type, followed by a comma separated list of identifiers with a semicolon at the very end. Variables of the same type don't need to be declared together. You could also split them up into multiple declarations of a single variable, each on its own line. In fact, this is a more common practice as it makes it easier to add a comment after each variable to describe its purpose.
Here are a few examples of variable declarations:
Variable Declarations with Definitions
Sometimes, you will want to ensure that a variable has an initial value for its first use. Conveniently, this can be done as part of the variable's declaration. The general form to both declare and define a variable in one step looks like this:
type identifier1 = value1, identifier2 = value2, … identifiern = valuen;
While initializing variables like this can be very convenient, there is a price to pay in terms of startup time. The C Runtime Environment startup code initializes these variables before your main() function is called. The initial values are stored along with program code in the non-volatile flash memory. When the device powers on, the startup code will loop through all the initialized variables and copy their initial values from flash into the variable's RAM location.
Here are a few examples showing the various ways variables can be declared alone or declared and defined together: