×

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

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

C++ Encapsulation

The following two essential components are present in all C++ programmes: Functions are the parts of a programme that perform actions, and they are termed programme statements (code).Program data is the...

4 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

Advanced C++ with Boost Library

The goal of the Boost Libraries is to be widely applicable and used in a variety of applications. For instance, they can in handy when working with huge numbers whose...

4 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

Assertions in C/C++

Assertions are the statements used to check presumptions which is made by the programmers. Example: Assertion is used to verify whether the malloc returned by the pointer is NULL or not. For...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.