Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I create an array of automatic variables?

In C++0x (ohh! read C++11), we have automatic type inference. One thing which made me curious was that I can't create an array of auto variables. For example:

auto A[] = {1, 2, 3, 4}; // Error!

Any ideas why this might have been disallowed?

like image 298
Rajendra Uppal Avatar asked Aug 18 '11 12:08

Rajendra Uppal


People also ask

Can I use Auto in array C++?

The possibly constrained (since C++20) auto specifier can be used as array element type in the declaration of a pointer or reference to array, which deduces the element type from the initializer or the function argument (since C++14), e.g. auto (*p)[42] = &a; is valid if a is an lvalue of type int[42].

How do you create an array size of variables?

If you want to create an array whose size is a variable, use malloc or make the size a constant. Show activity on this post. The compiler needs to know the size of the array while declaring it. Because the size of an array doesn't change after its declaration.

Can we initialize array with variable in C?

The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized.

Which storage class Cannot be used to initialise an array?

Automatic arrays, unlike automatic variables, cannot be initialized.


2 Answers

auto deduces every brace-enclosed initializer list to a std::initializer_list<T>. (See §7.1.6.4.6 including the example). Unfortunately you cannot initialize an array or even std::array from a std::initializer_list once you have obtained it, but you can use a std::vector.

#include <vector>
#include <array>
#include <initializer_list>

int main()
{
  auto x = {1,2,3};
  std::array<int, 3> foo1 = x; // won't work for whatever reason
  std::vector<int> foo2 = x; // works as expected
  return 0;
}

Of course this defeats the whole purpose of what you are trying to do.

I tried writing a work around called make_array but had to realize that this cannot ever work as the size of an initializer_list isn't part of its template arguments and so you only instantiate one make_array template for each T. This sucks.

template<typename T> 
auto make_array(const std::initializer_list<T>& x) 
     -> std::array<T, x.size()> { } // maaah

Well, apparently you can go for the variadic-template hack mentioned here How do I initialize a member array with an initializer_list?

like image 138
pmr Avatar answered Sep 25 '22 19:09

pmr


Because {1, 2, 3, 4} is purely a syntactic construct- it is not an expression and does not have a type. Therefore, auto cannot deduce its type from it.

like image 22
Puppy Avatar answered Sep 24 '22 19:09

Puppy