Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ raise an error when std array initialization is too small?

Tags:

c++

gcc

stdarray

Suppose I have an array of:

std::array<int, 6> {4,3,2};

Is it possible to raise an error or warning when this is the case? In some cases it might be useful to have this explicitly matching.

like image 594
Marnix Avatar asked Aug 16 '19 11:08

Marnix


People also ask

What happens when an array is initialized with a fewer Initializers as compared to its size B More Initializers as compared to its size?

If there are fewer initializers than elements in the array, the remaining elements are automatically initialized to 0.

What happens if an array initializer has more values than the size of the array?

An initializer-list is ill-formed if the number of initializer-clauses exceeds the number of members or elements to initialize.

Does C initialize arrays to 0?

An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero.

Is STD array initialized?

Initialization of std::array Like arrays, we initialize an std::array by simply assigning it values at the time of declaration. For example, we will initialize an integer type std::array named 'n' of length 5 as shown below; std::array<int, 5> n = {1, 2, 3, 4, 5};


1 Answers

You can use std::make_array or something like it to cause the types to differ

std::array<int, 6> = std::make_array(4,3,2);

gives this error in gcc:

<source>:30:53: error: conversion from 'array<[...],3>' to non-scalar type 'array<[...],6>' requested

like image 112
PeterT Avatar answered Oct 10 '22 10:10

PeterT