Home > database >  Are there cases in C where the auto keyword can't be replaced by an explicit type?
Are there cases in C where the auto keyword can't be replaced by an explicit type?

Time:10-29

I came across the following code:

auto x = new int[10][10];

Which compiles and runs correctly but I can't figure out what would be the type for defining x separately from the assignment.

When debugging the type shown is int(*)[10] for x but int (*) x[10]; (or any other combination I tried) is illegal.

So is a case that auto keyword cannot be replaced by an explicit type...?

CodePudding user response:

The type of x is int (*)[10]. There are different ways of figuring this out. The simplest is to just try assigning 5 to x and noticing what the error says:

error: invalid conversion from 'int' to 'int (*)[10]' [-fpermissive]
   13 |     x = 4;
      |         ^
      |         |
      |         int

Or just use static_assert:

static_assert(std::is_same<decltype(x), int(*)[10]>::value);

This means that if you want to explicitly create x(without using auto) then you can do it as:

int (*x)[10] = new int[10][10];

Are there cases in C where the auto keyword can't be replaced by an explicit type?

Now coming to the title, one example where auto cannot be directly replaced by explicitly writing a type is when dealing with unscoped unnamed enum as shown below: Demo

enum
{
    a,b,c
}obj;

int main()
{
//--vvvv----------->must use auto or decltype(obj)
    auto  obj2 = obj;
}

Similarly, when dealing with unnamed class. Demo.

CodePudding user response:

That is not a case in which you have to necessarily use auto.

But answering the question in the title, I can think of two cases where you need auto.

  1. As @IgorTandetnik said in a comment, lambas. auto f = [](){...};.

  2. returning of a local class, which has its uses.

auto f() {  // auto needed here
  struct A{
    double x;
    double y;
  };

  return A{...};
};
...
auto result = f();  // auto needed here
  • Related