The meaning of the auto keyword is changed in C++ 11.

Before C++ 11

Prior to C++ 11, it was under the list of storage class specifiers which tells the compiler where to store the variable and also the lifetime of a variable.

for example, if a variable is declared with the auto storage class specifier then it means the memory for that variable will get allocated in the stack space and the lifetime is towards the block in which it is declared.

// Before c++ 11

#include <stdio.h>

int main(void) {

	/* 
      'a' is accessible only inside this block &
      memory for this variable gets allocated in the stack space.
    */
	auto a = 10; 
	printf("%d", a);
	return 0;
}

Note: If we won’t specify any storage class specifier then by default compiler assumes it as an auto.  

After C++ 11

In C++ 11, the meaning of ‘auto‘ is completely changed. It is no more a storage class specifier. It is a type specifier in C++ 11.

If we specify a variable with type specifier auto, then the type of this variable will be automatically decided based on the value we assign.

#include <iostream>
using namespace std;

int main() {

	auto a = 10;
	std::cout << a << " " << sizeof(a) << std::endl;

	auto b = 20.4;
	std::cout << b << " " << sizeof(b) << std:: endl;

	return 0;
}

Here, variable ‘a‘ is automatically chosen as int and b as double.

Categorized in:

Tagged in: