Functions, Arrays and Strings

Article · 3:00

Declarations against definitions, how overloading picks a function, fixed arrays and why std::string replaced the C one.

A function has a declaration - the name, return type and parameter types - and a definition, which is the body. The compiler needs only the declaration to check a call; the linker needs the definition to produce a program. Keeping them apart is what lets a header describe an interface and a .cpp file implement it, and it is why "undefined reference" is a linker error rather than a compiler one.

Scope is lexical: a name declared inside braces exists until the closing brace. A local variable shadows an outer one of the same name, which compiles and is almost always a mistake - -Wshadow will tell you.

C++ allows overloading: several functions with the same name, distinguished by their parameters. The compiler picks by the argument types at each call. Note what is not part of the signature: the return type. Two functions differing only in what they return will not compile.

Default arguments let a caller omit trailing parameters - void log(const std::string& msg, int level = 1). Put them in the declaration, in the header, and not again in the definition.

Fixed arrays are a contiguous block of memory holding N elements of one type, with the size fixed at compile time. int scores[5]; reserves five ints side by side. Indexing starts at zero, and C++ does not check your bounds - scores[5] on a five-element array reads past the end, compiles cleanly and is undefined behaviour. Arrays also decay: pass one to a function and what arrives is a pointer to the first element, with the length lost. That is why C-style array code always passes a separate size, and why std::array and std::vector, which know their own length, are what you should actually use.

Strings are the clearest case of C++ improving on C. A C string is a char array ending in a zero byte, and every operation on it is manual, unbounded and a candidate for a buffer overflow. std::string from <string> owns its memory, grows as needed, frees itself, knows its own length and has the operations you want as member functions. Use it.

#include <iostream>
#include <string>
#include <array>

// --- Declaration: enough for the compiler to check calls. ---
double average(const int values[], int count);
void   log(const std::string& message, int level = 1);  // default here only

// --- Overloading: same name, different parameters. ---
int    square(int x)    { return x * x; }
double square(double x) { return x * x; }
// int square(double x) { ... }  // ERROR: return type is not part of it

int main()
{
    // --- Fixed arrays ---
    int scores[5]{90, 85, 77, 68, 95};   // braces: the rest would be 0
    std::cout << scores[0] << '\n';      // 90. Indexing starts at zero.
    // std::cout << scores[5];           // UB. Compiles. Reads past the end.

    // Multi-dimensional is just an array of arrays, laid out row by row:
    int grid[2][3]{{1, 2, 3}, {4, 5, 6}};
    std::cout << grid[1][2] << '\n';     // 6

    // std::array knows its own length and does not decay.
    std::array<int, 5> safe{90, 85, 77, 68, 95};
    std::cout << safe.size() << '\n';          // 5
    // safe.at(5) throws std::out_of_range instead of corrupting memory

    std::cout << average(scores, 5) << '\n';   // length passed separately

    // --- Overload resolution happens at compile time ---
    std::cout << square(3)   << '\n';    // 9    - the int version
    std::cout << square(3.0) << '\n';    // 9    - the double version

    // --- std::string ---
    std::string first{"Grace"};
    std::string last{"Hopper"};

    std::string full = first + " " + last;   // + concatenates
    std::cout << full                 << '\n';   // Grace Hopper
    std::cout << full.length()        << '\n';   // 12
    std::cout << full.substr(0, 5)    << '\n';   // Grace
    std::cout << full.find("Hopper")  << '\n';   // 6

    full.append(", rear admiral");
    if (full.find("admiral") != std::string::npos) {   // npos = not found
        std::cout << "found it\n";
    }

    log("starting");          // level defaults to 1
    log("disk full", 3);

    return 0;
}

// --- Definition: the body. The default argument is NOT repeated. ---
void log(const std::string& message, int level)
{
    std::cout << "[" << level << "] " << message << '\n';
}

double average(const int values[], int count)
{
    // values is a pointer here, not an array - the length is gone, which
    // is exactly why count has to be passed. sizeof(values) would give
    // the size of a pointer, not of the array.
    if (count <= 0) { return 0.0; }

    int total{0};
    for (int i = 0; i < count; ++i) { total += values[i]; }
    return static_cast<double>(total) / count;   // cast, or you get int /
}

Discussion

No questions on this topic yet. Sign in to ask the first one.