问题
In C99 the new complex types were defined. I am trying to understand whether a compiler can take advantage of this knowledge in optimizing memory accesses. Are these objects (A
-F
) of type complex float
guaranteed to be 8-byte aligned in memory?
#include "complex.h"
typedef complex float cfloat;
cfloat A;
cfloat B[10];
void func(cfloat C, cfloat *D)
{
cfloat E;
cfloat F[10];
}
Note that for D
, the question relates to the object pointed to by D
, not to the pointer storage itself. And, if that is assumed aligned, how can one be sure that the address passed is of an actual complex and not a cast from another (non 8-aligned) type?
UPDATE 1: I probably answered myself in the last comment regarding the D
pointer. B/c there is no way to know what address will be assigned to the parameter of the function call, there is no way to guarantee that it will be 8-aligned. This is solvable via the __builtin_assumed_aligned()
function.
The question is still open for the other variables.
UPDATE 2: I posted a follow-up question here.
回答1:
A float complex
is guaranteed to have the same memory layout and alignment as an array of two float
(§6.2.5). Exactly what that alignment will be is defined by your compiler or platform. All you can say for sure is that a float complex
is at least as aligned as a float
.
if that is assumed aligned, how can one be sure that the address passed is of an actual complex and not a cast from another (non 8-aligned) type?
If your caller passes you an insufficiently-aligned pointer, that's undefined behavior and a bug in their code (§6.3.2.3). You don't need to support that (though you may choose to).
来源:https://stackoverflow.com/questions/10928341/is-it-guaranteed-that-complex-float-variables-will-be-8-byte-aligned-in-memory