New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL
CLOSE
   C++  Auto Keyword  C++11  
   Technology    Programming

C++11 Auto Keyword

         
 OCTOBER 9, 2020   by Njadeja9

In simple terms, if we want to define the working of the Auto keyword, then it would be basically setting the variable type to initialize the value type of that variable or set the function return type as the value to be returned.

For Example:

auto a = 11 // will set the variable a as int type

auto b = 7.65 //will set the variable b as float

auto c = "abcdefg" // will set the variable c as string

Type inference easiness was one of the most awaited features that users were waiting for before the introduction of c++11. In modern-day dynamic programming, it was really becoming chaotic to define every variable and limit their working in programming runtime. Thus developers at Microsoft came to the conclusion of making the auto keyword more powerful. Even other programming languages such as python also did not require explicit declaration of variable type. So not only variables but all identifiers can also be assigned with the auto keyword.

Let's try to list out the advantages/benefits of using the auto keyword.

1. Easy to use:

The syntax is quite easy to use:

int a = 10;
// using auto keyword just like a data type
auto a = 10;

Just add keyword auto in-front of the variable/identifier and it will do its magic.

2. Works with all data types even with class pointers:

Let's see a code example,

#include <iostream>
#include <vector>

using namespace std;

class Demo{};

int main() {
    auto classdemo = Demo();
}

The example shows that you can even use an auto keyword with class identifiers as a template so that you don't have to declare everything again. It will directly create a container with the template of the previous class. Now you may get confused that we can create a child class for such scenarios but the counter would be what if both classes are to be used for different purposes like authentication table/code can be used for login activity as well as maintaining sessions in the practical world.

3. Best for using with iterators:

Let's see a code example,

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector < int > list {
        40,
        50,
        60,
        70,
        80,
        90,
        100
    };

    auto size = list.size();
    auto first_element = list.begin();

    cout << "Size of vector = " << size << endl;
    cout << "First element of the vector = " << * first_element << endl;
    cout << "Printing elements in vector using range-based for loop = ";

    for (auto element: list)
        cout << element << " ";

    cout << endl;
    cout << "Printing elements in vector using ordinary for loop = ";

    for (auto it = list.begin(); it != list.end(); ++it)
        cout << * it << " ";

    cout << endl;
    return 0;
}


$g++ -std=c++11 -o main *.cpp
$main

Size of vector = 7
First element of the vector = 40
Printing elements in vector using range-based for loop = 40 50 60 70 80 90 100
Printing elements in vector using ordinary for loop = 40 50 60 70 80 90 100

Here the example shows one vector of int numbers are printed, now when we use the auto keyword it adds a dynamic characteristic to the program. So in the future, if your list becomes of type double, you only need to change the values and nothing else, you will be good to go.

4. Using with return value of functions:

Let's see a code example,

#include <iostream>
#include <typeinfo>

using namespace std;

// trailing return type must be present, when you are
// using auto as return type.

template <class Temp>

    auto test(Temp value) -> decltype(value) {
        return value;
    }

// Another way to define function without auto

template <class Temp>

    Temp test1(Temp value) {
        return value;
    }

int main() {

    auto value = 10;
    auto word = "Hello World";

    cout << "typeid(value) = " << typeid(value).name() << ", value =" << value << endl;
    cout << "typeid(word) = " << typeid(word).name() << ", word = " << word << endl;
    cout << typeid(test("Hello there - test()")).name() << endl;
    cout << typeid(test1("Hello there - test1()")).name() << endl;

    return 0;
}


$g++ -std=c++11 -o main *.cpp
$main

typeid(value) = i, value =10
typeid(word) = PKc, word = Hello World
PKc
PKc

So the above program shows that using the auto keyword for return type in functions would require trailing return type and PKc will refer to the first character as character pointer for the string. So no matter what the values are of the type you would be getting the same type even in runtime with auto keyword

Its working can be enhanced by using the const keyboard with &(reference symbol)

The syntax for using it:

1) Const auto some_variable = some_value will make the some_variable const and will not allow any change to it in any given condition

2) Const auto& some_variable = some_reference will make the some_variable store a reference even if it contains garbage value, which you should avoid using if you are not sure about the changes you reference may undergo.

So these are all the cases where it would be helpful to use the auto keyword now a couple of areas where you need to avoid using the auto keyword as it may create havoc in the program if used incorrectly.

5. Ignored with initialization of reference variable

The auto keyword would be ignored if it is used with initialization of reference variable as a reference may change in the runtime.

Let us see one example of this :

const int a = 0;

auto& ref = a;

ref = 44; // error: const qualifier was not removed

Here auto will first make a reference to constant variable a but the reference value will be non-constant as it is initialized runtime by the compiler so when you try to change the reference value ref by assigning it some value like 44 you are actually trying to change the value at a which is constant as per declaration so this won't work

Secondly, even if you are trying to change the reference address then also the compiler will start giving error, for example:

int a = 42;

const int* ptr1 = &x;

auto ptr2 = ptr1;

*ptr2 = 43; // error: ptr2 is const int*

So when you update your pointer it doesn't really remain a pointer any longer and gives an error while initializing.

This was all about the auto keyword to be known before starting to use it.


RELATED POSTS



Subscribe and receive amazing posts directly in your inbox.