Understanding Data Types in C: A Guide to Variable Declaration
Explore the concept of data types in C, where every variable must be declared with a specific data type that defines the type and size of data it can store. Learn how to use the correct format specifier in the printf()
function to display variable values accurately.
C Data Types
Introduction to Data Types
In C, every variable must be declared with a specific data type. The data type determines the type and size of data that the variable can store. To display variables in the printf()
function, you also need to use a correct format specifier.
Example: Declaring Variables and Printing Values
Here’s an example of how to declare different data types and print their values:
Example
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
Output
5
5.990000
D
Basic Data Types
The data type defines the size and type of data the variable will store. Below are some common data types in C:
Data Type | Size | Description | Example |
---|---|---|---|
int |
2 or 4 bytes | Stores whole numbers, without decimals | 1 |
float |
4 bytes | Stores fractional numbers, with one or more decimals | 1.99 |
double |
8 bytes | Stores fractional numbers, with more precision | 1.99 |
char |
1 byte | Stores a single character, letter, or ASCII value | 'A' |
Basic Format Specifiers
Each data type has its own format specifier used in the printf()
function. Here are some common format specifiers:
Format Specifier | Data Type |
---|---|
%d or %i |
int |
%f or %F |
float |
%lf |
double |
%c |
char |
%s |
Used for strings (text), covered in a later chapter |
Important Notes
It’s crucial to use the correct format specifier for each data type. Using the wrong specifier can result in errors or even cause your program to crash.