copying C-style arrays and structure

Viewed 423

C++ does not allow copying of C-style arrays using =. But allows copying of structures using =, as in this link -> Copying array in C v/s copying structure in C.It does not have any credible answers yet. But consider following code

#include <iostream>
using namespace std;

struct user {
    int a[4];
    char c;
};

int main() {
    user a{{1,2,3,4}, 'a'}, b{{4,5,6,7}, 'b'};
    a = b;             //should have given any error or warning but nothing
    return 0;
}

Above code segment didn't gave any kind of errors and warnings, and just works fine. WHY? Consider explaining both questions(this one and the one linked above).

2 Answers

Yes, the code should work fine. arrays can't be assigned directly as a whole; but they can be assigned as data member by the implicity-defined copy assignment operator, for non-union class type it performs member-wise copy assignment of the non-static data member, including the array member and its elements.

Objects of array type cannot be modified as a whole: even though they are lvalues (e.g. an address of array can be taken), they cannot appear on the left hand side of an assignment operator:

int a[3] = {1, 2, 3}, b[3] = {4, 5, 6};
int (*p)[3] = &a; // okay: address of a can be taken
a = b;            // error: a is an array
struct { int c[3]; } s1, s2 = {3, 4, 5};
s1 = s2; // okay: implicity-defined copy assignment operator
         // can assign data members of array type
Related