×

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by looking into the initialization. So, it is good to declare the variable with the auto keyword. There are so many uses of auto keywords. These are variables, functions, pointers, iterators, templates, and many more.

Syntax:

map <int, int>::iterator itr;

How Does The Auto Keyword Work?

We discussed above that it automatically assigns and detects the value of the data type. It means we can replace the variable with auto keywords and the auto keyword has no limits.

Auto Used with Variables

The Auto keyword has the feature of automatically detecting the variable data type. The compiler will know the type of data type by looking into initialization.

Syntax

auto var = 5;

Example 1

#include <iostream>
#include <typeinfo>
#include <map>
#include <string>
#include <iterator>
auto sum(int x, int y) -> int
{
return x + y;
}
int main()
{
// Storing an int inside an auto variable
auto var_1 = 10;
// Storing a character inside an auto variable
auto var_2 = 'D';
std::cout << var_1 << std::endl;
std::cout << var_2 << std::endl;
// Storing Lambda function inside an auto variable
auto fun_sum = [](int a , int b)
{
return a+b;
};
std::cout << fun_sum(4, 5) << std::endl;
std::map<std::string, std::string> mapOfStrs;
// Insert data in Map
mapOfStrs.insert(std::pair<std::string, std::string>("first", "1"));
mapOfStrs.insert(std::pair<std::string, std::string>("sec", "2"));
mapOfStrs.insert(std::pair<std::string, std::string>("thirs", "3"));
// Iterate over the map and display all data;
// Create an iterator
std::map<std::string, std::string>::iterator it = mapOfStrs.begin();
while (it != mapOfStrs.end())
{
std::cout << it->first <<"::"<< it->second << std::endl;
it++;
}
// Iterate using auto
auto itr = mapOfStrs.begin();
while (itr != mapOfStrs.end())
{
std::cout << itr->first <<"::"<< itr->second << std::endl;
itr++;
}
auto x = 1;
// Cannot change the type of already initialized auto variable
// Error will occur at compile time
// x = "dummy";
// Can not declare an auto variable without initialization
// because its type is based on initializing value.
//auto a;
auto value = sum(3, 5);
std::cout << value << std::endl;
return 0;
}

Output:

10
D
9
first::1
sec::2
thirs::3
first::1
sec::2
thirs::3
8

Example 2

#include <iostream>


using namespace std;


// declare function with auto return type
auto add(int p, int q) {


// variable to store the sum
int sum = p + q;


// return the calculated sum
return sum;


}
int main() {


// initialize variables
int p = 6, q = 5;


// call function to add the variables
int sum = add(p, q);


// print sum
cout <<"The sum is "<< sum << endl;


return 0;
}

Output:

The sum is 11

Related Topics

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

C++ Convert Int to String

In fact, the conversion of numbers to strings or vice versa represents a significant paradigm change. We often need to convert a number to a string or a string to...

2 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.