When declaring arrays in C they can be declared normally like:
int arr[10]
or they can also be declared inside a structure like:
struct structArr{
int sArr[10];
}s1;
s1.sArr[]
instead of arr[]
, if so why?What I personally think is that arr[]
would be faster than s1.sArr[]
but I don't know whether I am correct or not moreover I don't have a technical answer for it.
I wouldn't expect there to be any difference, no.
The compiler "knows" that the offset of the sArr
field from the base address of s1
is 0, so I would guess that accesses can be done using the exact same sequence of instructions.
Of course, wrapping the array in a structure makes it possible to assign and pass/return it by value, which can be nice benefits.
The answer to your question depends upon the compiler and the optimizations.
With a recent GCC compiler with at least -O1
optimization, arr[]
won't be faster than s1.sArr[]
. Actually, if for some reason (e.g. its other fields) s1
is more aligned than arr
is, then it could happen (because of cache effects) that s1.sArr[]
might be slightly better (e.g. because more aligned to cache line size). But really from a performance point of view using arr[]
or s1.sArr[]
is (nearly mostly) the same.
For readability reasons things can be different. You may want to pack related items into some struct
. (And you may want to avoid having too much variable names).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With