0
votes

Subject : Initializing variable in C++

Good morning people, 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.

Thanks so much and I really appreciate the programming community for the ways in which you guys are helping new learning programmers like me. Cheers

1
See Initialization and follow the included links for more details. - Richard Critten
Your professor seems to have not noticed past 10 years in language development. Uniform initialization with curly braces is valid since C++11. If you don't manage to convince him to upgrade his compiler, you can use -std=c++98 to make your own compiler conform to the old standard. - Yksisarvinen
Testing on two different IDEs means nothing if they're using the same compiler. You could do all your testing in Atom only if you are able to install gcc and clang, for example. It's worth fighting for those points back, using the cppreference link posted. - sweenish
@NathanOliver sounds more like the professor needs the book. I suppose the book could be used as a metaphorical bludgeon, though. - user4581301

1 Answers

2
votes

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 can not be deduced.