1.2 Data Types and Variables
Most values in a computer program have a type. The type tells the compiler what the value represents and what operations make sense for it.
C is a statically typed language: a variable must declare its type before use, which tells the compiler how much memory to allocate and what operations the variable can take part in.
Common C basic types include:
- Integer types:
int,short,long - Floating-point types:
float,double - Character type:
char - Boolean type:
bool, which needs#include <stdbool.h>
Value ranges of the types
Different types can represent different ranges. The table below lists typical sizes and ranges on common platforms (exact values may vary by platform and compiler).
| Type | Common size | Typical range |
|---|---|---|
char | 1 byte | -128 to 127 (or 0 to 255) |
short | 2 bytes | -32,768 to 32,767 |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 |
long | 4 or 8 bytes | at least ±2.1×10⁹ (often ±9.2×10¹⁸ on 64-bit) |
float | 4 bytes | about ±3.4×10³⁸ (about 7 significant digits) |
double | 8 bytes | about ±1.7×10³⁰⁸ (about 15 significant digits) |
bool | 1 byte | 0 (false) or 1 (true) |
<limits.h>, and floating-point types in <float.h>. When a value may exceed the range, choose a larger type to avoid overflow.Variables
A variable is a name used to store data. In C, a variable must declare its type before use, and that type decides what kind of value it can hold.
int age = 18;
double height = 172.5;
char grade = 'A';Here, age holds an integer, so its type is int; height holds a decimal number, so its type is double; and grade holds a single character, so its type is char. Note that a single character is wrapped in single quotes.
Naming variables
Good variable names are clear and valid:
- Use letters, digits, and underscores, but do not start with a digit.
- Do not use C reserved keywords.
- Prefer meaningful English words.
Names like age, student_name, and total_score are easier to read than a or x1.
int total_score = 95;C keywords
Keywords are reserved by C and cannot be used as ordinary variable names.
Common keywords include:
int,char,float,double,voidif,else,switch,case,defaultfor,while,do,break,continuereturn,sizeof,const,staticstruct,enum,typedef,union
Using a keyword as a variable name would make C unable to tell whether you mean a language feature or an ordinary value.