Thuta Learning
C
BasicProgrammingBeginner

Data Types

CLesson 725 min

What you'll walk away with

  • Pick int, double, float or char for a value and print it with the matching format specifier
  • Explain why 7 / 2 is 3 while 7 / 2.0 is 3.5
  • Tell guaranteed sizes (sizeof(char) is 1) from platform-dependent ones (long is 4 bytes on Windows, 8 on Linux)
  • Use the fixed-width types from <stdint.h> and size_t when the exact width matters

Explain it simply

Explain it simply

A data type is like a label stuck on a variable. The label tells the compiler two things: how many bytes to set aside in memory, and how to interpret the bits inside those bytes. The very same 32 bits can be read as a whole number or as a decimal number, depending only on the type.

In everyday code you will mostly reach for four types: int for whole numbers such as a quantity, double for decimals such as a distance, char for a single character such as a grade letter, and float when memory is tight and precision matters less. Picking the right one up front keeps both your calculations and your printed output correct.

Problem → Why → Solution

The problem: the average that lost its half

Say you store 1999 cents for two items and want the average price per item. You even declare average as a double, so you expect 999.5. Instead the program prints a meaningless value, and the compiler printed a warning you scrolled past. Two type mistakes hide in these few lines: the division happens between two ints before the result ever reaches the double, and printf is told to read an int (%d) while it is handed a double.

average.c
#include <stdio.h>

int main(void) {
  int total_cents = 1999;
  int count = 2;
  double average = total_cents / count;   /* int / int: 999, not 999.5 */
  printf("Average: %d\n", average);       /* %d reads an int, gets a double */
  return 0;
}

Why does the type matter so much?

C decides how to compute an expression from the types of its operands, not from the variable that receives the result. 1999 / 2 is integer division, so the .5 is thrown away before the assignment turns 999 into 999.0. printf cannot see your variable's type at all: it trusts the format string, and a mismatch is undefined behaviour. With -Wall, GCC says so: format '%d' expects argument of type 'int', but argument 2 has type 'double'.

Core concept: size, range and meaning

Every C type answers three questions: how many bytes it occupies, which values fit in those bytes, and how operations on it behave. sizeof answers the first one. char is exactly 1 byte by definition, and a byte is 8 bits on every mainstream platform. The other integer types only have minimum guarantees: int must have at least 16 bits (roughly -32,767 to 32,767), long at least 32 bits and long long at least 64 bits.

The actual widths are chosen by the platform. On today's desktop and server compilers int is 32 bits (about plus or minus 2.1 billion), but long is 32 bits on 64-bit Windows and 64 bits on 64-bit Linux and macOS. Code that assumes a long can hold a 10-digit phone number works on one machine and silently breaks on the other. When the exact width matters, include <stdint.h> and use int32_t, uint8_t or int64_t, whose names state their width.

Each integer type comes signed (it can be negative) or unsigned (zero and up, with twice the positive range). The two behave differently at their limits. Unsigned arithmetic wraps around modulo 2 to the power N, so 0u - 1 becomes the largest unsigned value. Overflowing a signed int is undefined behaviour: the program may print a wrong number, crash, or be optimised in surprising ways. Rely on neither; pick a type with room to spare.

For decimals, float gives about 6-7 significant digits and double about 15-16, so double is the sensible default. Neither stores most decimal fractions exactly: 0.1 is really the nearest binary fraction, which is why money is often kept as whole cents in an integer. Finally, sizes and counts use size_t, the unsigned type that sizeof itself returns, printed with %zu.

TypeTypical useprintf
intcounts, scores%d
long longvery large whole numbers%lld
unsigned intvalues that are never negative%u
doublemeasurements, averages%f, %.2f
charone character%c (its code with %d)
size_tsizeof results, lengths%zu
Mental model: a labelled box of bytes
  1. Type fixes the box size (sizeof)
  2. Type fixes which values fit
  3. Operand types pick the arithmetic
  4. Format specifier must match the type

The compiler reads the label on the box; printf only reads the label you write in the format string.

General pattern

c
type name = initial_value;

unsigned int count = 0u;      /* u suffix: unsigned literal */
long long big = 0LL;          /* LL suffix: long long literal */
double ratio = 0.0;           /* decimal point: double literal */
float small = 0.0f;           /* f suffix: float literal */
char letter = 'A';            /* single quotes: one character */

printf("%u %lld %f %c %zu\n", count, big, ratio, letter, sizeof(type));

Write the type first, then the name and an initial value. Literal suffixes (u, LL, f) and the decimal point tell the compiler the literal's own type. Every printf conversion must match its argument.

Example: each type with its specifier

The example declares one variable of each everyday type and prints it with its matching specifier. The last four printf lines are experiments: they show float's limited precision, integer versus floating-point division, and two sizes you can check. sizeof(int) prints 4 on mainstream compilers, but the standard only promises at least 16 bits.

data_types.c
#include <stdio.h>

int main(void) {
  int items = 5;
  double distance = 12.7564;
  float ratio = 0.1f;
  char initial = 'T';

  printf("Items: %d\n", items);
  printf("Distance: %.3f km\n", distance);
  printf("Initial: %c (code %d)\n", initial, initial);
  printf("float  0.1 -> %.10f\n", ratio);
  printf("double 0.1 -> %.10f\n", 0.1);
  printf("7 / 2 = %d, 7 / 2.0 = %.1f\n", 7 / 2, 7 / 2.0);
  printf("sizeof(char) = %zu, sizeof(int) = %zu\n", sizeof(char), sizeof(int));
  return 0;
}

Code breakdown

  1. Lines 5-6float ratio = 0.1f;

    distance is a double and ratio is a float. The f suffix makes 0.1f a float literal; without it, 0.1 is a double literal.

  2. Line 10printf("Distance: %.3f km\n", distance);

    %.3f prints a double with 3 decimals, so 12.7564 becomes 12.756. A float argument is promoted to double on its way into printf, so %f works for both (%lf is accepted too). scanf is different: it needs %lf for a double.

  3. Line 11printf("Initial: %c (code %d)\n", initial, initial);

    A char is really a small integer. %c shows it as a character and %d shows its code: 'T' is 84 in ASCII.

  4. Lines 12-13printf("float 0.1 -> %.10f\n", ratio);

    Zoomed in to 10 decimals, the float shows 0.1000000015 and the double shows 0.1000000000. Neither stores 0.1 exactly, but the double's error is too small to see at this precision.

  5. Line 147 / 2, 7 / 2.0

    With two int operands, 7 / 2 is integer division and gives 3. 2.0 is a double, so 7 is converted to double first and the result is 3.5.

  6. Line 15sizeof(char), sizeof(int)

    sizeof yields a size_t, which is printed with %zu. char is always 1; int is 4 here, but that is the platform's choice, not a promise of the standard.

You should see
Items: 5
Distance: 12.756 km
Initial: T (code 84)
float  0.1 -> 0.1000000015
double 0.1 -> 0.1000000000
7 / 2 = 3, 7 / 2.0 = 3.5
sizeof(char) = 1, sizeof(int) = 4

Limits, fixed-width types and conversions

<limits.h> gives your platform's real integer limits as macros such as INT_MAX, INT_MIN and UINT_MAX. <stdint.h> gives types such as int32_t, int64_t and uint8_t whose names carry their bit count; when they exist, their width is guaranteed exact.

Converting between types follows rules. Storing a double in an int drops the fraction toward zero, so (int)-3.99 is -3 (it does not round). Storing a value that does not fit in an unsigned type wraps it modulo, so 300 becomes 44 in an unsigned char. For a signed type that is too small the result is implementation-defined, and converting an out-of-range double to an int is undefined behaviour.

limits_demo.c
#include <stdio.h>
#include <limits.h>
#include <stdint.h>

int main(void) {
  printf("int: %d to %d\n", INT_MIN, INT_MAX);
  printf("unsigned int max: %u\n", UINT_MAX);
  printf("int64_t: %zu bytes, uint8_t: %zu byte\n", sizeof(int64_t), sizeof(uint8_t));

  double reading = -3.99;
  int truncated = (int)reading;
  int big = 300;
  unsigned char level = big;
  printf("(int)%.2f = %d\n", reading, truncated);
  printf("300 stored in unsigned char = %d\n", level);
  return 0;
}

Do not test INT_MAX + 1

Once a signed value overflows, the standard no longer guarantees anything about the program. Even if your machine shows -2147483648, a different optimisation level can change the result. Use long long or int64_t for values that might approach the limit.

In real projects

Where this shows up in real projects

In real C code, choosing a type is a design decision. Embedded firmware reads a sensor into a uint16_t because the hardware register is exactly 16 bits. A network protocol parser stores a packet length in a uint32_t because the wire format says 4 bytes, not "whatever int happens to be". Plain int would work on your laptop and be wrong on a microcontroller where int is only 16 bits.

Business software has its own rules. Prices are usually stored as integer cents (int64_t or long long) so that adding 0.10 ten times gives exactly 1.00, while double is kept for measurements such as distances, temperatures and ratios, where tiny rounding errors do not matter. Array lengths and buffer sizes travel as size_t, which is why functions like strlen return one. When you join a new project or target a new board, print the sizeof of the types you rely on and compile with -Wall -Wextra, so format and conversion mismatches are caught before they ship.

Common mistakes

Common mistakes

1. Assuming long is 64 bits

long is 8 bytes on 64-bit Linux and macOS but only 4 bytes on 64-bit Windows, so a value like 5000000000 fits on one and overflows on the other. When you need 64 bits, say so with long long or int64_t.

2. Mismatched printf specifiers

Printing a double or a long with %d is undefined behaviour and prints garbage. GCC's -Wall reports format '%d' expects argument of type 'int', but argument 2 has type 'long int' and even suggests %ld. Treat these warnings as errors.

3. Expecting decimals from integer division

double avg = total / count; still truncates when both are ints, because the division happens before the assignment. Convert one operand first: (double)total / count.

Best practices

Best practices

  • Default to double for decimals; choose float only when memory really is tight.
  • Use <stdint.h> types for data whose width is fixed by a file format, a protocol or a hardware register.
  • Keep money in integer cents, not in a double.
  • Always compile with -Wall -Wextra and leave no format warning unfixed.

Mini challenge

Mini challenge: a well-typed receipt line

Write a program that describes one line of a shopping receipt, choosing a suitable type for every value and printing each with the correct specifier.

  • Store a quantity of 3 (int), a unit price of 2.75 (double), the size letter 'M' (char) and stock id 120045 (int32_t from <stdint.h>)
  • Print the line total with 2 decimals
  • Divide 7 loyalty points (an int) by the quantity without losing the fraction
  • Print the stock id with %ld after converting it to long, and its size with %zu
  • Compile with -Wall -Wextra and get zero warnings
receipt_line.c
#include <stdio.h>
#include <stdint.h>

int main(void) {
  /* TODO: quantity, unit price, size letter */
  /* TODO: total_points (int) and stock_id (int32_t) */

  /* TODO: line total = quantity * unit price */
  /* TODO: points per item, keeping the fraction */

  /* TODO: print the size letter, the total and the points (2 decimals) */
  /* TODO: print the stock id and how many bytes it uses */
  return 0;
}

Expected: It compiles without warnings and prints these four lines: Size: M Line total: 8.25 Points per item: 2.33 Stock id 120045 uses 4 bytes

Show hint

Cast before dividing: (double)total_points / quantity. sizeof works on a variable as well as on a type name, and it gives a size_t.

Show solution
receipt_line.c
#include <stdio.h>
#include <stdint.h>

int main(void) {
  int quantity = 3;
  double unit_price = 2.75;
  char size_code = 'M';
  int total_points = 7;
  int32_t stock_id = 120045;

  double line_total = quantity * unit_price;
  double avg_points = (double)total_points / quantity;

  printf("Size: %c\n", size_code);
  printf("Line total: %.2f\n", line_total);
  printf("Points per item: %.2f\n", avg_points);
  printf("Stock id %ld uses %zu bytes\n", (long)stock_id, sizeof stock_id);
  return 0;
}

Quick quiz 1 / 3

What does printf("%d\n", 7 / 2); print?

Quick quiz 2 / 3

With GCC on 64-bit Windows, what does sizeof(long) normally report?

Quick quiz 3 / 3

Which call correctly prints double price = 4.5; with two decimals?

What to remember

  • A type decides the number of bytes, the values that fit and how operations behave.
  • char is always 1 byte, but int and long only have minimum guarantees: long is 4 bytes on Windows and 8 on Linux.
  • int / int drops the fraction; convert one operand to double when you need decimals.
  • printf specifiers must match the argument type (%d, %u, %lld, %f, %c, %zu); a mismatch is undefined behaviour.
  • Use <stdint.h> types such as int32_t when the width must be exact, and size_t for sizes.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Data Types | Thuta Learning