Lesson contents

C — Data types and integer quantities

A C type determines which values an object can hold and how expressions using it behave. Character arrays preserve the written form of an identifier.

A simple example

Tell a number from text

  1. Start with 2 and "2"
  2. Do this Add or join
  3. Result 4 and 22
Adding two numbers gives 4. Joining two copies of the text gives the two characters 22.
lesson.c
#include <stdio.h>

int main(void) {
    printf("%d\n", 2 + 2);
    printf("%s%s\n", "2", "2");
}
Output
4
22
Advertisements

Choosing a data type

Type or declaration Example Use
char[] "007" A null-terminated character array can store a printed identifier.
int 125 Holds a whole-number quantity within the implementation’s int range.
double 0.25 Represents a floating-point measurement.
bool true Include <stdbool.h> in C17 to use bool, true, and false.
size_t sizeof(int) Unsigned type for sizes and array allocation counts.

Keep a product identifier and its price distinct

Keep the printed code 007 as text. Store the quantity and the price in cents as whole numbers so multiplication gives an exact total for this order. The final null byte terminates the character string. Use %s for that string and %d for the int total. In a production billing calculation, choose a type wide enough for the largest total.

Product label: 007. Quantity × price: 3 × 125¢. Line total: 375¢.
Keep a product code intact

A school shop sells three packs of paper at 125 cents each. Its scanner must print the code 007 exactly as it appears on the shelf. Keep the code as text and multiply the numeric quantity and price.

Run the example

Use a C17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
lesson.c
#include <stdio.h>

int main(void) {
    const char product[] = "007";
    int quantity = 3;
    int price_cents = 125;
    printf("%s: %d cents\n", product, quantity * price_cents);
    return 0;
}
Output
007: 375 cents

The label retains both leading zeros. Three units at 125 cents cost 375 cents. The display joins the values only after the calculation.

Try it yourself

Change the code to 010 and the quantity to zero. What should stay visible?

Check your answer

The label stays 010 and the total becomes 0 cents. Treating the identifier as a number would lose its written form.

WG14 C language draft (PDF)

Related tags

  • C
  • data types
  • text
  • integer values