Create Variables in C
What is a Variable?
A variable is a named storage location in the computer’s memory that holds a value. In C, every variable has a type that determines the size of memory it uses and the operations that can be performed on it.
Variables allow programs to store, retrieve, and manipulate data dynamically during execution.
Type sizes are implementation-defined. The common sizes listed below are typical on many modern systems, but always prefer `sizeof(type)` to know the exact size on your platform.
Type | Description | Memory Size (Typical) | Example |
---|---|---|---|
int | Stores whole numbers | 4 bytes | int age = 25; |
float | Stores decimal numbers (single precision) | 4 bytes | float pi = 3.14f; |
double | Stores larger decimal numbers (double precision) | 8 bytes | double g = 9.81; |
char | Stores a single character (code unit) | 1 byte | char grade = 'A'; |
Declaring vs. Initializing
• **Declaration**: Tells the compiler to reserve memory for a variable of a specific type. Example: `int x;`
• **Initialization**: Assigns an initial value *at the moment of declaration*. Example: `int y = 10;`
If a variable is declared but not initialized, it holds an **indeterminate** value. Reading that value before assigning something is **undefined behavior**.
#include <stdio.h>
int main(void) {
int age; // declaration only (uninitialized)
age = 20; // assignment after declaration
int count = 10; // declaration with initialization
printf("Age (after assignment): %d\n", age);
printf("Count (initialized): %d\n", count);
return 0;
}
Age (after assignment): 20 Count (initialized): 10
Checking Sizes with sizeof
Use the `sizeof` operator to check the exact size of each type on your platform.
#include <stdio.h>
int main(void) {
printf("sizeof(int) = %zu\n", sizeof(int));
printf("sizeof(float) = %zu\n", sizeof(float));
printf("sizeof(double)= %zu\n", sizeof(double));
printf("sizeof(char) = %zu\n", sizeof(char));
return 0;
}
Constants vs Variables
Variables can change their values during program execution. Constants, defined using `const`, cannot.
Example: `const float PI = 3.14159f;` (attempting to assign `PI = 3.2f;` would be a compile-time error).
`const` gives type safety and scope; remember that `const` variables are not compile-time integer constants in standard C (use `enum` or `#define` where a compile-time constant is required).