Initialising array elements in curly braces??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; }

26th Jun 2022, 10:36 AM
Edward Finkelstein
Edward Finkelstein - avatar
2 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
26th Jun 2022, 11:12 AM
Abhay
Abhay - avatar
+ 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/
26th Jun 2022, 2:26 PM
MO ELomari