C/C++ Basics

Functions and Parameter Passing

Function parameters are copied by default; a caller must explicitly grant access when a function should modify its object.

What is Functions and Parameter Passing?

Function parameters are copied by default; a caller must explicitly grant access when a function should modify its object.

Compare pass-by-value, pointers, and references.

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>

void swap_ints(int *left, int *right) {
    int temporary = *left;
    *left = *right;
    *right = temporary;
}

int main(void) {
    int a = 4, b = 9;
    swap_ints(&a, &b);
    printf("%d %d\n", a, b);
    return 0;
}
Expected output
9 4
C++
Run code →
main.cpp
#include <iostream>

void swap_ints(int& left, int& right) {
    int temporary = left;
    left = right;
    right = temporary;
}

int main() {
    int a = 4, b = 9;
    swap_ints(a, b);
    std::cout << a << ' ' << b << '\n';
}
Expected output
9 4

C and C++ comparison

C passes an address and dereferences it. C++ references provide alias syntax while preserving mutation semantics. const parameters document read-only access.

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.