what is the difference between these 2 types of initializing an integer?

what is the different between:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main()
{
    int x{1};
    return 0;
     
}


and

1
2
3
4
5
6
7
8
9
10
11
12
13

#include <iostream>

using namespace std;

int main()
{
    int x=1;
    return 0;
     
}

int x{1}; Direct initialisation: https://en.cppreference.com/w/cpp/language/direct_initialization

int x = 1 ; Copy initialisation: https://en.cppreference.com/w/cpp/language/copy_initialization

For a simple type like int, or when the type of the initialiser expression is the same as the type of the object being initialised, there is no practical difference between he two.
In such a short example you cannot spot any difference, but the uniform initializer ‘{}’ helps a lot to prevent narrowing:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>


int main()
{
    unsigned a = 1u;

    // Fine for GCC with these flags:
    // -Wall -Wextra -Wpedantic:
    int b = a;

    int c { a };   // warning, no matter what flags!

    std::cout << b << c << '\n';    // just to avoid 'unused variable' warning
}

Topic archived. No new replies allowed.