Chapter 05Beginner

Data Types & Variables

Learn to store different kinds of data: numbers (int), decimals (float), and characters (char). Understand how much memory each type uses.

20 min readUpdated 2024-12-16
data typesintfloatchardoublevariablesconstantssizeof

What You Will Learn

  • Declare variables to store data
  • Choose the right data type (int, float, char)
  • Know the size and range of each type
  • Create constants that never change

01Introduction

In C, every piece of data you store needs a data type. The data type tells the computer what kind of information you're storing and how much memory to use.

There are three main data types you'll use most often:

Data TypeWhat It StoresExample Values
intWhole numbers (no decimals)42, -17, 0, 1000
floatDecimal numbers3.14, -0.5, 99.99
charSingle character'A', 'z', '@', '5'

See Them in Action

Here's a simple program that uses all three data types:

data_types_example.c
C
1#include <stdio.h>
2
3int main() {
4 // Storing a whole number
5 int age = 25;
6
7 // Storing a decimal number
8 float price = 19.99;
9
10 // Storing a single character
11 char grade = 'A';
12
13 // Printing them out
14 printf("Age: %d years\n", age);
15 printf("Price: $%.2f\n", price);
16 printf("Grade: %c\n", grade);
17
18 return 0;
19}

Output:

Age: 25 years
Price: $19.99
Grade: A

Key Points

  • • Use int for counting things: age, score, quantity
  • • Use float for measurements: price, weight, temperature
  • • Use char for single letters or symbols (use single quotes!)

02Prerequisites

  • Completed the Basic Syntax tutorial
  • A working C compiler installed
  • Understanding of program structure and main() function

03Integer Type (int)

The int (short for "integer") is the workhorse of C programming. It stores whole numbers — numbers without decimal points, like 1, 42, -100, or 0.

🎯 When to Use int

✓ Perfect for:

  • • Counting things (loops, items)
  • • Ages, scores, quantities
  • • Array indices
  • • Any whole number math

✗ Don't use for:

  • • Prices with cents ($19.99)
  • • Scientific measurements
  • • Anything needing decimals
  • • Very large numbers (>2 billion)
int

Integer Data Type

Stores whole numbers

Size

4 bytes = 32 bits

On most modern systems (32-bit and 64-bit)

Format Specifier

%d or %i

Used in printf() and scanf()

Integer Range and Variations

TypeSize (bits)Size (bytes)Minimum ValueMaximum Value
short int162-32,76832,767
int324-2,147,483,6482,147,483,647
long int32 or 644 or 8Platform dependentPlatform dependent
long long int648-9,223,372,036,854,775,8089,223,372,036,854,775,807
unsigned int32404,294,967,295

How Range is Calculated

For a signed integer with n bits: Range is -2^(n-1) to 2^(n-1) - 1
For 32 bits: -2^31 to 2^31 - 1 = -2,147,483,648 to 2,147,483,647

int_example.c
C
1#include <stdio.h>
2#include <limits.h> // Contains INT_MIN, INT_MAX
3
4int main() {
5 // Integer declarations
6 int age = 25;
7 int negative = -100;
8 int count = 0;
9
10 // Display values
11 printf("Age: %d\n", age);
12 printf("Negative: %d\n", negative);
13 printf("Count: %d\n", count);
14
15 // Size of int on this system
16 printf("\nSize of int: %zu bytes (%zu bits)\n", sizeof(int), sizeof(int) * 8);
17
18 // Range of int (from limits.h)
19 printf("INT_MIN: %d\n", INT_MIN);
20 printf("INT_MAX: %d\n", INT_MAX);
21
22 return 0;
23}

04Floating-Point Type (float)

The float data type stores decimal numbers (numbers with fractional parts). It uses the IEEE 754 standard for representing floating-point numbers.

float

Floating-Point Data Type

Stores decimal/fractional numbers

Size

4 bytes = 32 bits

Single precision floating-point

Format Specifier

%f

Use %.2f for 2 decimal places

Floating-Point Range and Precision

TypeSize (bits)PrecisionRange (Approximate)
float326-7 decimal digits±3.4 × 10^38
double6415-16 decimal digits±1.7 × 10^308
long double80-12818-21 decimal digitsPlatform dependent

32-bit Float Structure (IEEE 754)

1 bit - Sign
8 bits - Exponent
23 bits - Mantissa

This structure allows float to represent very large and very small numbers, but with limited precision.

float_example.c
C
1#include <stdio.h>
2#include <float.h> // Contains FLT_MIN, FLT_MAX
3
4int main() {
5 // Float declarations (use 'f' suffix)
6 float price = 99.99f;
7 float temperature = -40.5f;
8 float pi = 3.14159f;
9
10 // Double for more precision (default for decimals)
11 double precise_pi = 3.14159265358979;
12
13 // Display values
14 printf("Price: %.2f\n", price);
15 printf("Temperature: %.1f\n", temperature);
16 printf("Pi (float): %.6f\n", pi);
17 printf("Pi (double): %.14f\n", precise_pi);
18
19 // Size comparison
20 printf("\nSize of float: %zu bytes (%zu bits)\n", sizeof(float), sizeof(float) * 8);
21 printf("Size of double: %zu bytes (%zu bits)\n", sizeof(double), sizeof(double) * 8);
22
23 // Range of float (from float.h)
24 printf("\nFLT_MIN: %e\n", FLT_MIN);
25 printf("FLT_MAX: %e\n", FLT_MAX);
26
27 return 0;
28}

Precision Warning

Float can only store about 6-7 significant digits accurately. For precise calculations (like money), use double or integer arithmetic. Example: 0.1 + 0.2 might not equal exactly 0.3!

05Character Type (char)

The char data type stores a single character. Internally, characters are stored as integer values using the ASCII encoding system.

char

Character Data Type

Stores single characters or small integers

Size

1 byte = 8 bits

Smallest data type

Format Specifier

%c

Use %d for ASCII value

Range

-128 to 127

Or 0-255 unsigned

Common ASCII Values

CharacterASCII ValueDescription
'0' - '9'48 - 57Digit characters
'A' - 'Z'65 - 90Uppercase letters
'a' - 'z'97 - 122Lowercase letters
' '32Space character
'\0'0Null character (string terminator)
'\n'10Newline character
char_example.c
C
1#include <stdio.h>
2
3int main() {
4 // Character declarations (use single quotes!)
5 char letter = 'A';
6 char digit = '5';
7 char symbol = '@';
8 char newline = '\n';
9
10 // Characters are stored as numbers (ASCII)
11 printf("Letter: %c (ASCII: %d)\n", letter, letter);
12 printf("Digit: %c (ASCII: %d)\n", digit, digit);
13 printf("Symbol: %c (ASCII: %d)\n", symbol, symbol);
14
15 // Character arithmetic works!
16 char next = letter + 1; // 'A' + 1 = 'B'
17 printf("Next letter: %c\n", next);
18
19 // Convert uppercase to lowercase
20 char lower = letter + 32; // 'A' + 32 = 'a'
21 printf("Lowercase: %c\n", lower);
22
23 // Size of char
24 printf("\nSize of char: %zu byte (%zu bits)\n", sizeof(char), sizeof(char) * 8);
25
26 return 0;
27}

06Derived Data Types (Overview)

Derived data types are built from primitive types. They allow you to create more complex data structures to store collections of data or custom types.

Primitive vs Derived Types

Primitive Types

Basic building blocks

intfloatchardouble
Derived Types

Built from primitives

ArraysStringsStructuresPointersUnionsEnums
Derived TypeWhat It IsExample
ArrayCollection of same-type elements stored in contiguous memoryint numbers[5];
StringArray of characters ending with null character ('\0')char name[] = "Hello";
StructureGroup of different data types under one namestruct Person { ... }
PointerVariable that stores memory address of another variableint *ptr = &num;
UnionMembers share same memory location (one value at a time)union Data { int i; float f; }
EnumNamed integer constants for readable codeenum Color { RED, GREEN }

Quick Preview

derived_preview.c
C
1#include <stdio.h>
2
3int main() {
4 // Array - collection of integers
5 int scores[3] = {85, 90, 78};
6
7 // String - array of characters
8 char name[] = "Alice";
9
10 // Printing
11 printf("Name: %s\n", name);
12 printf("First score: %d\n", scores[0]);
13
14 return 0;
15}

07Format Specifiers

Format specifiers are special placeholders used in printf() and scanf() functions to tell C how to format or read data. Each data type has its own format specifier.

How Format Specifiers Work

printf() - Output

Converts data to text for display

printf("Age: %d", age);
scanf() - Input

Reads text and converts to data

scanf("%d", &age);

Integer Format Specifiers

SpecifierData TypeDescriptionExample Output
%dintSigned decimal integer-42, 100
%iintSame as %d (integer)-42, 100
%uunsigned intUnsigned decimal integer42, 100
%ldlong intLong signed integer2147483647
%lldlong long intLong long integer9223372036854775807
%hdshort intShort integer32767
%ointOctal (base 8)52 (for 42)
%x, %XintHexadecimal (base 16)2a, 2A (for 42)

Floating-Point Format Specifiers

SpecifierData TypeDescriptionExample Output
%ffloat, doubleDecimal notation (6 decimal places)3.141593
%.2ffloat, double2 decimal places3.14
%e, %Efloat, doubleScientific notation3.14e+00
%g, %Gfloat, doubleShortest of %f or %e3.14159
%Lflong doubleLong double precision3.141592653589793

Character & String Format Specifiers

SpecifierData TypeDescriptionExample Output
%ccharSingle characterA, z, @
%schar[] / char*String (null-terminated)Hello World

Special Format Specifiers

SpecifierData TypeDescriptionExample Output
%ppointer (void*)Memory address0x7ffd5e8e3a4c
%zusize_tsizeof() result4, 8
%%-Print literal % sign%

Width and Precision Modifiers

Format specifiers can include width and precision to control output formatting:

FormatMeaningExampleOutput
%5dMinimum width 5, right-alignedprintf("%5d", 42)" 42"
%-5dMinimum width 5, left-alignedprintf("%-5d", 42)"42 "
%05dWidth 5, zero-paddedprintf("%05d", 42)"00042"
%.2f2 decimal placesprintf("%.2f", 3.14159)"3.14"
%8.2fWidth 8, 2 decimal placesprintf("%8.2f", 3.14)" 3.14"
%.5sMax 5 characters from stringprintf("%.5s", "Hello World")"Hello"
format_specifiers.c
C
1#include <stdio.h>
2
3int main() {
4 // Integer format specifiers
5 int num = 42;
6 printf("Decimal: %d\n", num); // 42
7 printf("Octal: %o\n", num); // 52
8 printf("Hexadecimal: %x\n", num); // 2a
9 printf("Hexadecimal: %X\n", num); // 2A
10
11 // Floating-point format specifiers
12 float pi = 3.14159f;
13 printf("Default: %f\n", pi); // 3.141590
14 printf("2 decimals: %.2f\n", pi); // 3.14
15 printf("Scientific: %e\n", pi); // 3.141590e+00
16
17 // Character and string
18 char ch = 'A';
19 char name[] = "Alice";
20 printf("Character: %c\n", ch); // A
21 printf("String: %s\n", name); // Alice
22
23 // Width and alignment
24 printf("Right align: %10d\n", num); // 42
25 printf("Left align: %-10d|\n", num);// 42 |
26 printf("Zero pad: %05d\n", num); // 00042
27
28 // Special
29 printf("Address: %p\n", &num); // 0x7ffd...
30 printf("Percent: 100%%\n"); // 100%
31
32 return 0;
33}

Quick Reference: Data Type → Format Specifier

int

%d

float

%f

double

%lf

char

%c

string

%s

long

%ld

pointer

%p

size_t

%zu

Warning: Mismatched Format Specifiers

Using the wrong format specifier causes undefined behavior! For example, using %d for a float or %f for an int will produce garbage output or crashes.

08Declaring and Initializing Variables

A variable is a named storage location in memory. Before using a variable, you must declare it (tell the compiler its type and name).

Declaration

Tells compiler the variable exists and its type.

declaration.c
C
int age; // Declared only
float price; // Contains garbage value!
char grade;

Initialization

Assigns a value at declaration time.

initialization.c
C
int age = 25; // Declared + initialized
float price = 9.99f;
char grade = 'A';
variables.c
C
1#include <stdio.h>
2
3int main() {
4 // === DECLARATION ===
5 int count; // Declaration only (garbage value!)
6 float temperature; // Not initialized
7 char letter; // Contains random data
8
9 // === INITIALIZATION (Recommended!) ===
10 int age = 25; // Declare + initialize
11 float price = 19.99f; // 'f' suffix for float
12 char grade = 'A'; // Single quotes for char
13
14 // === ASSIGNMENT (After Declaration) ===
15 count = 100; // Now has a value
16 temperature = 36.5f;
17 letter = 'X';
18
19 // === MULTIPLE DECLARATIONS ===
20 int x, y, z; // All are int
21 int a = 1, b = 2, c = 3; // All initialized
22 float width = 10.5f, height = 20.0f;
23
24 // === DISPLAY VALUES ===
25 printf("Age: %d\n", age);
26 printf("Price: $%.2f\n", price);
27 printf("Grade: %c\n", grade);
28 printf("Dimensions: %.1f x %.1f\n", width, height);
29
30 return 0;
31}

Warning: Uninitialized Variables

In C, uninitialized variables contain garbage values (random data left in memory). Always initialize your variables to avoid unpredictable behavior!

Default "Null" Values in C

Unlike some languages, C doesn't have a built-in null for primitive types. Here are the common "zero" or "empty" values:

Data TypeZero/Null ValueExampleNotes
int0int x = 0;Zero is the standard empty value
float0.0ffloat f = 0.0f;Zero with float suffix
double0.0double d = 0.0;Zero for double
char'\0'char c = '\0';Null character (ASCII 0)
pointerNULLint *p = NULL;From stdlib.h or stddef.h
null_values.c
C
1#include <stdio.h>
2#include <stdlib.h> // For NULL
3
4int main() {
5 // Initializing with "null" or zero values
6 int count = 0; // Integer zero
7 float total = 0.0f; // Float zero
8 double amount = 0.0; // Double zero
9 char empty = '\0'; // Null character
10 int *pointer = NULL; // Null pointer
11
12 // Check for zero/null values
13 if (count == 0) {
14 printf("Count is zero\n");
15 }
16
17 if (empty == '\0') {
18 printf("Character is null (ASCII 0)\n");
19 }
20
21 if (pointer == NULL) {
22 printf("Pointer is NULL\n");
23 }
24
25 return 0;
26}

09Constants and #define

Constants are values that cannot be changed after they're set. C provides two ways to create constants: the const keyword and the #define preprocessor directive.

const Keyword

  • • Has a data type
  • • Stored in memory
  • • Can be used with debugger
  • • Follows scope rules
  • • Type-checked by compiler
const.c
C
const int MAX = 100;
const float PI = 3.14f;
const char NEWLINE = '\n';

#define Macro

  • • No data type
  • • Text replacement (no memory)
  • • Processed before compilation
  • • Global scope
  • • No type checking
define.c
C
#define MAX 100
#define PI 3.14
#define NEWLINE '\n'
constants.c
C
1#include <stdio.h>
2
3// === #define MACROS (Before main, no semicolon!) ===
4#define MAX_SIZE 100
5#define PI 3.14159
6#define GREETING "Hello, World!"
7#define SQUARE(x) ((x) * (x)) // Macro with parameter
8
9int main() {
10 // === const VARIABLES ===
11 const int maxAge = 120;
12 const float taxRate = 0.08f;
13 const char grade = 'A';
14
15 // Using #define constants
16 printf("Max Size: %d\n", MAX_SIZE);
17 printf("PI: %f\n", PI);
18 printf("%s\n", GREETING);
19 printf("5 squared: %d\n", SQUARE(5));
20
21 // Using const variables
22 printf("Max Age: %d\n", maxAge);
23 printf("Tax Rate: %.2f%%\n", taxRate * 100);
24 printf("Grade: %c\n", grade);
25
26 // ERROR: Cannot modify constants!
27 // maxAge = 150; // Compiler error!
28 // MAX_SIZE = 200; // Compiler error!
29
30 return 0;
31}

When to Use Which?

Use const for typed constants with scope control. Use #define for simple values, conditional compilation, and macros. Modern C prefers const for safety.

10C Keywords (Reserved Words)

📝 Quick Reference

Keywords are reserved words with special meanings in C. You cannot use them as variable names!

intfloatcharvoidifelseforwhilereturnbreakstaticconst...and 20 more

📖 For the complete list of all 32 keywords with detailed explanations, see the Keywords in C Tutorial.

⚠️ Remember

int int = 5; is invalid — "int" is a keyword! Use descriptive names like int count = 5;

11Summary

What You Learned:

Primitive Data Types:

  • int: 32 bits (4 bytes), range ±2.1 billion
  • float: 32 bits (4 bytes), ~7 decimal precision
  • char: 8 bits (1 byte), stores ASCII characters

Format Specifiers:

  • %d, %i: Integers | %f: Float/Double | %c: Character
  • %s: Strings | %p: Pointers | %x: Hexadecimal
  • Width/Precision: %5d (width), %.2f (2 decimals), %05d (zero-pad)

Key Concepts:

  • Null Values: int=0, float=0.0f, char='\0'
  • Constants: Use const for type safety, #define for macros

12Next Steps

Now that you understand data types and variables, you're ready to learn about Operators and Expressions — how to perform calculations and manipulate data.