C Programming Variables

Last modified by Microchip on 2023/11/10 11:00

Information

Variable

A variable is the combination of a data types and an identifier (name) that represents one or more memory locations used to hold a program's data.

Looking at the "A Simple C Program" page, we can observe the three topics of this section in action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    #include <stdio.h>

   #define PI 3.14159

   int main(void)
    {
         float radius, area;

        //Calculate area of circle
       radius = 12.0;
         area = PI * radius * radius;
        printf("Area = %f", area);
    }

Line 7 shows an example of a variable declaration (actually two variable declarations). A variable is simply a container for holding data, where the container occupies one or more bytes in the microcontroller's memory (typically RAM).

variable container

A variable must be declared before it can be used. The declaration of a variable consists of two parts:

  1. data type (or just simply a type) that serves two purposes:
    1. Tells the compiler how to handle or manipulate the data stored in the variable. In the example, the word float is one of several data types we'll discuss later in this section.
    2. Tells the linker how much memory to reserve to store the contents of the variable.
  2. An identifier (or name) that will be used to uniquely identify the variable whenever we want to access or modify its contents. The words radius and area in the example are identifiers.

To the right is a visual representation of how three variables might be stored in the 16-bit wide data memory of a PIC24 family device (there wouldn't actually be gaps between them).

The first variable, warp_factor, is of type int which is defined as a 16-bit value in the MPLAB® XC16 Compiler, so it takes one complete word (two bytes) of data memory.

The second variable letter is of type char which is almost always an 8-bit value and only compilers with Unicode support might define it otherwise. So, it takes up one byte or half of a word of data memory. If other char type variables were declared, a second one would be packed into the same word as the first, so both bytes would be occupied.

The third variable length is of type float which is usually a 32-bit value with most compilers. It takes up two full words or 4-bytes of data memory. Its data is also encoded (not shown) in a modified form of the IEEE-754 floating point format, so it needs to be handled differently from int and char type variables.

variable illustration