c++variablesinitializationbraced-init-list

int count{0}. Can I initialize a variable using curly braces in C++?


I am in first year in BSc Computer Science. I received a comment from my Professor on my recently submitted assignment . I initialized an int variable to zero : int count{0};. The book assigned to us in the course gives only one way to initialize a variable by using an assignment statement. int count = 0;

I don't remember where I learnt the curly braces method to initialize the variable. According to my professor , this is not a legal way to do it. My program runs without any errors in Atom and also on online debugger. I always check my program for errors from two different platforms. So, I am confused whether my method was wrong and was missed by the compiler or this method is legal but not considered standard.

Any clarification will be helpful. Also any advice on good programming practices for debugging, so it doesn't happen again as I lost 4 marks from a 10 mark assignment.


Solution

  • Here is how you may initialize the variable count of the type int with zero

    int count = 0;
    int count = { 0 };
    int count = ( 0 );
    int count{ 0 };
    int count( 0 );
    int count = {};
    int count{};
    

    You may not write

    int count();
    

    because this will be a function declaration.

    If to use the specifier auto then these declarations

    auto count = { 0 };
    auto count = {};
    

    must be excluded from the above list because in this case in the first declaration the variable count will have the type std::initializer_list<int> and in the second declaration the type of the variable can not be deduced.

    Pay attention to that the initialization of scalar objects with a braced list was introduced in C++ 11.