#include <iostream>
#include <algorithm> // For std::copy and std::fill_n
// Helper function to print array elements using C++17 template parameter deduction
template <typename T, std::size_t N>
void printCArray(const char* title, const T(&arr)[N]) {
std::cout << "--- " << title << " ---\n[ ";
for (std::size_t i = 0; i < N; ++i) {
std::cout << arr[i] << (i + 1 < N ? ", " : " ");
}
std::cout << "]\n\n";
}
int main() {
// -------------------------------------------------------------------------
// EXAMPLE 1: Zero/Value Initialization
// Zero-initializes all elements. Safe, clear, and avoids garbage memory.
// -------------------------------------------------------------------------
int zeroInit[5] = {};
printCArray("1. Zero / Value Initialization", zeroInit);
// -------------------------------------------------------------------------
// EXAMPLE 2: Direct List Initialization (Full)
// Explicitly provides values for every element.
// -------------------------------------------------------------------------
int fullInit[5] = {10, 20, 30, 40, 50};
printCArray("2. Direct List Initialization (Full)", fullInit);
// -------------------------------------------------------------------------
// EXAMPLE 3: Partial List Initialization
// Unspecified trailing elements are automatically zero-initialized.
// -------------------------------------------------------------------------
int partialInit[5] = {1, 2}; // Elements will be [1, 2, 0, 0, 0]
printCArray("3. Partial List Initialization", partialInit);
// -------------------------------------------------------------------------
// EXAMPLE 4: Automatic Size Deduction
// Let the compiler deduce the array size from the initializer count.
// -------------------------------------------------------------------------
int deducedInit[] = {100, 200, 300, 400}; // Size deduced as 4
printCArray("4. Automatic Size Deduction", deducedInit);
// -------------------------------------------------------------------------
// EXAMPLE 5: Algorithm-Based Fill (std::fill_n)
// Useful for setting non-zero default values at runtime.
// -------------------------------------------------------------------------
int filledInit[5];
std::fill_n(filledInit, 5, 42); // Sets all 5 elements to 42
printCArray("5. Standard Algorithm Fill (std::fill_n)", filledInit);
}
/*
run:
--- 1. Zero / Value Initialization ---
[ 0, 0, 0, 0, 0 ]
--- 2. Direct List Initialization (Full) ---
[ 10, 20, 30, 40, 50 ]
--- 3. Partial List Initialization ---
[ 1, 2, 0, 0, 0 ]
--- 4. Automatic Size Deduction ---
[ 100, 200, 300, 400 ]
--- 5. Standard Algorithm Fill (std::fill_n) ---
[ 42, 42, 42, 42, 42 ]
*/