+ 2

Why do i get an error when running this

#include <iostream> using namespace std; int main(){ int arr[5]; arr = {1, 2, 3, 4, 5}; cout << arr[3]; return 0; } // instead of running the below code(i mean the right one) when i run the code on top why do i get an error?? #include <iostream> using namespace std; int main(){ int arr[5] = {1, 2, 3, 4, 5}; cout << arr[3]; return 0; }

7th Sep 2017, 12:29 PM
Sanoj Silva
Sanoj Silva - avatar
9 Réponses
+ 1
@enzo, it is the same with struct, this syntax can be used only during the declaration of a variable
7th Sep 2017, 1:10 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
oh sorry my bad there should be a semicolon but even with the semicolon it gives an error @Enzo
7th Sep 2017, 12:40 PM
Sanoj Silva
Sanoj Silva - avatar
+ 2
Oh yes ! I just didn't know the English name ! It is the same as a static array declaration but the values can be of different types !
7th Sep 2017, 3:53 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
It is the same thing, only usable at the definition of a variable return {1, "plop"}; would work with a return type like that : struct{int i; char s[50]}
7th Sep 2017, 3:55 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
According to google you cant asign arrays like this. I dont understand it very well myself but you either asign it in the initialization or apparently its possible to do this using a struct but i have never tried it. The other option is to just asign the values one at a time.
7th Sep 2017, 1:06 PM
Enzo
Enzo - avatar
+ 1
what about compound literals? I see lots of people using it but when I try it, it errors.
7th Sep 2017, 1:37 PM
Enzo
Enzo - avatar
0
you didnt put a semi-colon after the arr [5] line
7th Sep 2017, 12:33 PM
Enzo
Enzo - avatar
0
Hum, I do not get what you mean by compound literal (my English isn't all that good) :/
7th Sep 2017, 3:44 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
I just found out about it today so im not even sure what it is :p you can google it if you want but dont worry about the question.
7th Sep 2017, 3:48 PM
Enzo
Enzo - avatar