1

I've started learning c++ from learncpp.com.

In second lesson where functions are explained, there is a strange variable initialization in the first example: int input{ 0 };

My IDE (CLion) claims: > Expected ";" at the end of declaration.

If I run this code (using gcc), it works well. Same if I remove the parentheses.

So what's the meaning of {} after the variable name?

Here is the full example:

#include <iostream>

int getValueFromUser()
{
    std::cout << "Enter an integer: ";
    int input{ 0 };
    std::cin >> input;  

    return input;
}

int main()
{
    int num { getValueFromUser() };

    std::cout << num << " doubled is: " << num * 2 << '\n';

    return 0;
}
Artem
  • 563
  • 3
  • 17
  • 3
    If you want to learn C++, I suggest you do so from one of these [good C++ books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Jul 29 '19 at 17:50
  • To avoid those warnings, make sure to set your IDE language settings to use at least C++11. – 0x5453 Jul 29 '19 at 17:52

2 Answers2

2

The title is misleading, Perhaps you want to ask the difference between {0} and =0, not why a variable should be initialized. Please clarify the question.

int x{0}; initializes the variable to 0, equal to int x = 0;. It's a feature added in C++11.

Best practises include that initialization takes places in variables. If you leave the integer without initialization and since it has no default constructor, the compiler will not initialize it.

This means that by the time you use it will have an undefined value. This may not be a problem if you first write to it, but may be a serious issue if you forget that it's uninitialized and assume that it has a defaul value.

Here is a trivial bug many times seen in code:

int n;
int factorial;
cin >> n; 
for(int i = 1; i <=n; i++)
    factorial *= i; // Whops, factorial started with undefined value 

Correct is to init it with 1 of course.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
1

To answer the title Why should I use “int input{0};” instead of “int input;”

int input{0}; or int input = 0; initializes the variable input with 0. int input; does not initialize the value input is indeterminate. Which might result in undefined behavior if that variable is used later on:

int input;          
int var = input;           // undefined behavior

More details about default initialization on cppreference.com

t.niese
  • 39,256
  • 9
  • 74
  • 101