Open In App

C++ 17 | New ways to Assign values to Variables

Improve
Improve
Like Article
Like
Save
Share
Report

C++ 17 introduced many new ways to declare a variable. Earlier assignment and declaration was done using “=”

Example:

int a = 5;

But now 2 more ways are introduced in C++17. They are:

  1. Constructor initialization: In this way, the value of the variable is enclosed in parentheses ( () ). In this way, value can be passed in two ways shown below.




    #include <iostream>
    using namespace std;
      
    // Driver Code
    int main()
    {
      
        // Declaring the variable in parentheses
        // Method 1
        int a(5);
        cout << "a = " << a;
      
        // Declaring the variable in parentheses
        // Method 2
        int b = (10);
        cout << endl
             << "b = " << b;
      
        return 0;
    }

    
    

    Output:

    a = 5
    b = 10
    

    Explanation
    In C++ 17, the variable can be declared by providing values through parenthesis too. The difference between constructor initialization and the old normal way of initialization is that it will always return last value in the parenthesis no matter what it’s magnitude or sign is.

    For example,

    a=(2, 21, -50, 1)

    The value stored in a would be 1.

  2. Uniform initialization: In this way, the value of the variable is enclosed in curly braces ( {} ) instead of parentheses. In this way, the value can be passed in two ways shown below.




    #include <iostream>
    using namespace std;
      
    int main()
    {
      
        // Declaring the variable in curly braces
        // Method 1
        int a{ 3 };
        cout << "a = " << a;
      
        // Declaring the variable in curly braces
        // Method 2
        int b = { 7 };
        cout << endl
             << "b = " << b;
      
        return 0;
    }

    
    

    Output:

    a = 3
    b = 7
    

    Unlike Constructor initialization, this assigning method can only take one value in the braces. Providing multiple values would return a compile error.

    For example,

    int b={7, 12};
    

    Output

    prog.cpp: In function 'int main()':
    prog.cpp:9:12: error: scalar object 'b' requires one element in initializer
     int b={7, 12};
                ^
    


Last Updated : 06 Mar, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads