C Programming Variable Declarations and Definitions

Last modified by Microchip on 2024/01/31 15:03

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 identifier1identifier2, … 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:

int x, y, z;
float warpFactor;
char text_buffer[10];   // This is an array variable - will discuss later in class
unsigned index;        // int is optional when modified - this is an unsigned int

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 = value1identifier2 = 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 the 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:

unsigned int x;
unsigned y = 12;
int a, b, c;
long int myVar = 0x12345678;
long z;
char first = 'a', second, third = 'c';  // first and third initialized, second not
float big_number = 6.02e+23;