C/C++ Basics

Data Types and Formatted Output

C and C++ share fundamental numeric types, but their preferred formatting mechanisms differ.

What is Data Types and Formatted Output?

C and C++ share fundamental numeric types, but their preferred formatting mechanisms differ.

Declare integer and floating-point values and print them safely.

Important points

  • Compile with warnings enabled and fix every warning.
  • Know the lifetime and type of every value.
  • Validate input and keep array bounds explicit.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>

int main(void) {
    int items = 7;
    double price = 3.5;
    printf("items=%d total=%.2f\n", items, items * price);
    return 0;
}
Expected output
items=7 total=24.50
C++
Run code →
main.cpp
#include <iomanip>
#include <iostream>

int main() {
    int items = 7;
    double price = 3.5;
    std::cout << "items=" << items << " total="
              << std::fixed << std::setprecision(2) << items * price << '\n';
}
Expected output
items=7 total=24.50

C and C++ comparison

printf requires a format specifier that matches each promoted argument. C++ stream insertion selects an overload from the value type and iomanip controls precision.

C

C exposes small procedural APIs and makes representation details explicit.

C++

C++ retains the low-level model while adding safer library types and abstractions.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Add invalid and boundary-value inputs.
  • Compile with -Wall -Wextra -Wpedantic.
  • Move reusable declarations into a header and implementation file.