c++variable-assignmentassignassignment-operatorcurly-braces

What is the difference between equal (=) and curly braces ({}) on C++ assignments?


Just wanted to understand the assignment differences between = and { }

Given this code snippet:

#include "std_lib_facilities.h"

class Token {
public:
        char kind;
        double value;
        string name;
        Token ( char ch ) : kind{ch} { } 
        Token ( char ch, double val ) : kind {ch}, value {val} { } 
        Token ( char ch, string n ) : kind {ch}, name {n} { } 
};


int main ( void )
{
        char ch; 

        cin >> ch;    

        // Token = ch; // Fails to compile - see below.
        Token {ch};

        return 0;
}

What is the different meaning between: Token {ch}; versus Token = ch; What does this error means?

error: expected unqualified-id

ERROR WHEN USING `Token =  ch;`.
$ c++ -std=c++11 -o poc_Token_assignments poc_Token_assignments.cpp
poc_Token_assignments.cpp:20:8: error: expected unqualified-id
        `Token =  ch;`
              ^
1 error generated.

Non-error when using curly braces (Token {ch};):

$ c++ -std=c++11 -o poc_Token_assignments poc_Token_assignments.cpp
$   (COMPILED PERFECTLY USING THOSE {} CURLY BRACES)

Solution

  • It is pretty simple, look at these three lines:

    5;          // Creates an int literal which goes away right away
    int = 5;    // Syntax error: Cannot assign a value to a type
    int a = 5;  // Correct: Store the value 5 in the variable a
    

    Now for your code:

    Token {ch} is similar to the first line. A Token is created and then destroyed right away.

    Token = ch similar to the second line: You cannot assign a value to a type.

    What I think you want is one of these:

    Token t = ch;
    Token t{ch};
    Token t(ch);
    

    For the difference between the two last I will refer you to: What are the advantages of list initialization (using curly braces)? or perhaps better; a good book.