4 ms·
This gets weird when you compare it to how structs work in C. Both are complex data types, so I sometimes forget that array semantics are totally different to s
by rossy 10y ago
This gets weird when you compare it to how structs work in C. Both are complex data types, so I sometimes forget that array semantics are totally different to struct/union semantics. Unlike arrays, in ANSI C, structs are real value types. You can pass them by-value to functions, return them by-value from functions and assign them by-value to variables of the same type. Also, structs never work like pointers to themselves. You have to dereference the pointer or use the -> syntactic sugar to access a member of a pointer to a struct.
Value type semantics enable some neat things, for example, you can zero all the members of a struct by assigning a compound literal to it. You can also make simple structs, like three uint8_ts for an RGB colour, and use them just like they were primitive types. In comparison, it seems almost archaic that you have to break out memset() and memcpy() to zero and move arrays.
- mojuba 10y agoWorth noting that you can always wrap an array in a structure and kick it around in your program happily, as if it's how the language should've been. struct { int a[5]; } arr5 = {{4, 3, 2}}; What's a bit weird though, is that while initialization like above is possible, assignment of a contsant is not as smooth in C, you will have to typedef your structure and use it in a typecast expression: typedef struct { int a[5]; } Array5; ... arr5 = (Array5){{4, 3, 2}};
- gpderetta 10y agoYou can actually drop the extra brackets (at least in C++, but IIRC also in C). C++11 has array<T, size_t> which has proper value semantics. It is implemented exactly like your structure above, so no overhead, and also has a proper operator== and assignment via initializer list.
- ScottBurson 10y agoYes, and there's another inconsistency here as well. Arrays and pointers into arrays are accessed with the same syntax: char a[3], *pa = a; ... a[0] ... pa[0] ... In contrast, with a struct, you have to know which one you have and use the correct operator: struct { int x; } s, *ps = &s; ... s.x ... ps->x ... To be consistent, they could either have made '.' work in both cases, or forced you to write things like '(*pa)[0]'.