In C, a variable is a named location in memory used to store data. Before using a variable, you must declare its data type, which tells the compiler how much memory to allocate and how to interpret the stored bits.
1. Declaring and Initializing Variables
A. Declaration
Declaration reserves memory space and tells the compiler the variable’s name and type.
Syntax: dataType variableName;
int age;
float score;
char initial;
B. Initialization
Initialization assigns an initial value to the variable during or immediately after its declaration.
Syntax: dataType variableName = value;
int height = 180;
double pi = 3.14159;
2. Core Data Types
C is a strongly typed language, meaning the type must be strictly defined. The core types handle integers, floating-point numbers, and characters.
| Data Type | Description | Size (Typical) | Range |
int | Standard integer. | 4 bytes | $\pm 2$ billion |
char | Single character or small integer. | 1 byte | $-128$ to $127$ (or $0$ to $255$) |
float | Single-precision floating-point number. | 4 bytes | Approx. $10^{-37}$ to $10^{37}$ |
double | Double-precision floating-point number (more accurate). | 8 bytes | Approx. $10^{-308}$ to $10^{308}$ |
3. Type Modifiers
The core types can be modified to fit specific needs, primarily to change the size or sign (positive/negative).
| Modifier | Use Case | Example |
short | To use less memory for smaller integers. | short int smallNum; |
long | To handle very large integers or doubles. | long long bigNum; |
signed | Default; allows positive and negative values. | signed int x; |
unsigned | Only allows positive values, effectively doubling the positive range. | unsigned int uNum; |
Note: When using
short,long,signed, orunsigned, theintkeyword is often optional (e.g.,unsigned long num;is the same asunsigned long int num;).
4. Constants (const)
A constant is a variable whose value cannot be changed after initialization. This is useful for defining fixed values like mathematical constants or size limits.
Syntax: const dataType constantName = value;
const float TAX_RATE = 0.08f;
const int MAX_USERS = 100;
Tip: By convention, constants are often named using ALL CAPS to distinguish them from regular variables.
5. Type Casting
Type casting is the explicit conversion of a value from one data type to another.
Syntax: (newDataType) expression
If you divide two integers, the result will be an integer (truncation). To get an accurate floating-point result, you must cast one of the operands to a float or double.
int total_items = 7;
int boxes = 2;
// Standard integer division (result: 3)
float avg1 = total_items / boxes;
// Type casting (result: 3.5)
float avg2 = (float)total_items / boxes;
