C Programming Variables
Looking at the "A Simple C Program" page, we can observe the three topics of this section in action.
2
3
4
5
6
7
8
9
10
11
12
13
14
#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).
A variable must be declared before it can be used. The declaration of a variable consists of two parts:
- A data type (or just simply a type) that serves two purposes:
- 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.