+ 1
Initialising array elements in curly braces???
Specifically in the code below, what's the difference between the first way and the second way? #include <iostream> using namespace std; int main() { int arr[] = {0,-1,2}; arr[0]={0-arr[1]}; //First way cout << arr[0] << '\n'; arr[0]=0-arr[1]; //Second way cout << arr[0] << '\n'; return 0; }
3 Answers
+ 2
from the following post i see it has to do with implicit conversion of airthmetic values (i.e. double to int which will generate warning)
https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.educative.io/answers/declaring-a-variable-with-braces-in-cpp&ved=2ahUKEwjSyP6g_Mr4AhXxjOYKHZR4Ay8QFnoECBcQAQ&usg=AOvVaw2kNjVySXVNbtsFuMZOoIZU
+ 2
assignment using curly braces prohibits <implicit narrowing conversions> among built-in types.
for example if the value of an expression in a curly braces isnât guaranteed to be expressible by the type of the object being initialized or assigned, the code wonât compile:
https://godbolt.org/z/xfWMbKoEe
however assignment using parentheses doesnât check for narrowing conversions:
https://godbolt.org/z/GvsKz9KqG
have a look at this article by herb Sutter:
https://herbsutter.com/2013/05/09/gotw-1-solution/