Data Types and Variables in C
What is a Data Type?
A data type specifies the type of data a variable can hold, the amount of memory it occupies, and the operations that can be performed on it.
---
Primary (Built-in) Data Types
| Data Type | Size | Range | Format Specifier |
|---|---|---|---|
int | 2 or 4 bytes | -32768 to 32767 (2 bytes) | %d |
float | 4 bytes | 3.4e-38 to 3.4e+38 | %f |
double | 8 bytes | 1.7e-308 to 1.7e+308 | %lf |
char | 1 byte | -128 to 127 | %c |
void | 0 bytes | No value | — |
---
Type Modifiers
Modifiers change the range or sign of basic data types:
| Modifier | Example | Size | Range |
|---|---|---|---|
short | short int | 2 bytes | -32768 to 32767 |
long | long int | 4/8 bytes | wider range |
unsigned | unsigned int | 4 bytes | 0 to 65535 |
signed | signed int | 4 bytes | -32768 to 32767 |
---
Variables
A variable is a named memory location that stores a value.
Syntax:
data_type variable_name;
data_type variable_name = value; /* with initialisation */
Rules for variable names:
- Must begin with a letter or underscore
- Can contain letters, digits, underscores
- Cannot use reserved keywords
- Case-sensitive (
age≠Age)
Example:
#include <stdio.h>
int main() {
int age = 20;
float marks = 85.5;
char grade = 'A';
printf("Age: %d\n", age);
printf("Marks: %.1f\n", marks);
printf("Grade: %c\n", grade);
return 0;
}
---
Constants
A constant is a value that cannot be changed during program execution.
#define PI 3.14159 /* macro constant */
const int MAX = 100; /* const keyword */
---
Keywords in C
C89 has 32 reserved keywords:
auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while