Using GCC you can do something like this.
void foo(MyStruct *a, const MyStruct *b)
{
memcpy(&a[0], b, sizeof(*a));
memcpy(&a[1], b, sizeof(*a));
memcpy(&a[2], b, sizeof(*a));
}
When writing portable code, using modern C compilers *, this can optimize to output the same asm
as ...
void foo(MyStruct a[3], const MyStruct *b)
{
a[0] = *b;
a[1] = *b;
a[2] = *b;
}
My question is, is it reasonable to assume the function call to memcpy
will always be be optimized out?
I'm asking this because I was considering to use memcpy
in a macro which gets instantiated many times with size known at compile time. If this will call memcpy
on some platforms, I'd prefer to avoid calling it at all.
eg: Implement generic swap macro in C
* modern C compilers (GCC/Clang/MSVC/ICC). with standard/safe optimization level set.