Search code examples
c++initialization

unable to include multiple expressions in initialization of a variable c++


On cppreference.com, it is stated something like that:

For each declarator, the initializer may be one of the following: ( expression-list ) (1) = expression (2) { initializer-list } (3)

  1. comma-separated list of arbitrary expressions and braced-init-lists in parentheses

But in my code

int main(){

    int a,b=5,c(a,b);
    return 0;
}

when I try to compile it, the following error occurs

...error: expression list treated as compound expression in initializer [-fpermissive]

My question: If the list of multiple expressions is allowed in such style of initialization, then why the compiler is not accepting it with the variable c?

What am I missing?


Solution

  • All right, let's look at this:

    int main(){
    
        int a,b=5,c(a,b);
        return 0;
    }
    

    What do you expect c(a,b) to actually do?

    Let's simplify this just slightly:

    int main(){
    
        int a,b=5;
        int c(a,b);
        return 0;
    }
    

    This will generate the same syntax error, but it now stands alone. So...

    Your code would work if there were a constructor for int that took two ints as parameters. This would also compile:

    int c(int a, int b);
    

    But in that case, you're actually defining a function.

    Also, this works:

    int main() {
        int a = 5;
        int b = 10;
        int c(b);
    
        std::cout << "C == " << c << std::endl;
    }
    

    That works because an int can be initialized from a single int. But you're getting an error because you can't initialize an int from two other ints.

    This works:

    #include <iostream>
    
    class MyClass {
    public:
        MyClass(int a, int b): value(a + b) {}
        int value;
    };
    
    int main() {
        int a = 5;
        int b = 10;
        MyClass c(a, b);
    
        std::cout << "C == " << c.value << std::endl;
    }
    

    And maybe that's what the article you read was trying to tell you. Note: cpppreference is NOT a good site for learning C++. Get a good book.