I\'m beginner to c++
I think this is trivial question but I didn\'t find answer
why this code gives an error ? while if we intialized the array in one line byt
why this code gives an error ?
Because you may not assign to an array variable. Arrays can not be passed by value to functions or operators as such. When used in a context where a pointer is expected, they decay to a pointer to first element.
It's not possible to copy an array (or initializer list) to another using only pointers to the first elements of each array. Such operation requires information about the size of the arrays.
There's a good analysis on why the assignment is not allowed here. It's about array to array assignment, but I suppose it applies to initializer list as well.
while if we intialized the array in one line byte x[2] = {78,82} works correctly ?
It works because you may initialize an array variable (with list initialization in this case). Remember that =
does different things depending on if it's used in a declaration or a non-declaration statement. In a declaration it's syntax for initialization, in non-declaration statement it's the assignment operator.
what is the difference of the x pointer in both cases ?
x
is not a pointer, it's an array. There is only difference is that in one case you initialize the objects in x
and in the other you leave it uninitialized and then attempt to assign an an initializer list to it which is not possible.