How to initialize different types of arrays to zero in C++

1 Answer

0 votes
#include <iostream>
#include <array>
#include <atomic>

/*
    This program demonstrates several ways to initialize arrays of different
    types to zero. It covers:
      - Built‑in numeric types
      - User‑defined types with a zero state
      - std::atomic<int>

    Each initialization is wrapped in a function to keep main() focused.
    The goal is to show clear, expressive patterns that experienced developers
    commonly use.
*/

// A simple struct that can be "zeroed" by assigning 0 to its fields.
struct Point {
    int x;
    int y;
};

// Initialize an array of built‑in numeric types.
// Using fill() is concise and efficient.
void initNumeric(std::array<int, 5>& arr) {
    arr.fill(0);  // sets all elements to zero
}

// Initialize an array of user‑defined types.
// We assign a zero-state object to each element.
void initStruct(std::array<Point, 5>& arr) {
    for (auto& p : arr) {
        p = Point{0, 0};  // explicit zero state
    }
}

// Initialize an array of atomic integers.
// store() is used to write values safely.
void initAtomic(std::array<std::atomic<int>, 5>& arr) {
    for (auto& a : arr) {
        a.store(0);  // atomic write
    }
}

// Print numeric array
void printNumeric(const std::array<int, 5>& arr) {
    for (const auto& v : arr) {
        std::cout << v << " ";
    }
    std::cout << "\n";
}

// Print struct array
void printStruct(const std::array<Point, 5>& arr) {
    for (const auto& p : arr) {
        std::cout << "(" << p.x << "," << p.y << ") ";
    }
    std::cout << "\n";
}

// Print atomic array
void printAtomic(const std::array<std::atomic<int>, 5>& arr) {
    for (const auto& a : arr) {
        std::cout << a.load() << " ";
    }
    std::cout << "\n";
}

int main() {
    // Arrays of different types
    std::array<int, 5> numeric{};
    std::array<Point, 5> points{};
    std::array<std::atomic<int>, 5> atomics;

    // Initialize all arrays to zero
    initNumeric(numeric);
    initStruct(points);
    initAtomic(atomics);

    // Print results
    printNumeric(numeric);
    printStruct(points);
    printAtomic(atomics);
}


/*
run:

0 0 0 0 0 
(0,0) (0,0) (0,0) (0,0) (0,0) 
0 0 0 0 0 

*/

 



answered Aug 26 by avibootz
...