TITLE: portably determining alignment (Newsgroups: comp.std.c++, 23 Jun 98) BRIAN: Brians0 > In November, 1997, there was a long thread (subject: "alignment") > about how to find the alignment of any type in a portable and/or > standard way. After reading the thread on dejanews, i couldn't > determine whether or not a solution was found. There were tricks > involving template classes, the offsetof() macro, and > a suggestion of adding an alignof() operator (similiar to sizeof). All > these had one drawback or another and it seems that the standard would > have to be changed in order to impliment any of these methods. Can > anybody please tell the "standard" way to do it, as it stands now? TRIBBLE: David R Tribble I assume by "standard way" you mean a way that conforms to the standard language, i.e., doesn't do anything non-conforming. The way we determine datatype alignment across several platforms is to declare a structure for each type which requires padding bytes. Then we examine the offset that the padding bytes produce. An example will illustrate: struct align_long { char pad; long x; }; int long_alignment() { struct align_long s1; char * p1; char * p2; p1 = (char *) &s1; // Get address of struct p2 = (char *) &s1.x; // Get address of long within struct return (p2 - p1); // Get member offset/alignment } On byte-aligned machines, the compiler will not add padding bytes between 'pad' and 'x' in the structure. (Usually; you may have to set a compiler flag to enable this behavior, since the compiler may go ahead and word-align struct members for efficiency even though the CPU doesn't require word alignment.) For these kinds of CPUs, the difference 'p2-p1' will be 1, meaning that longs are aligned on the nearest byte boundary. On word-aligned machines, the compiler will add padding bytes between 'pad' and 'x' to force 'x' to be aligned (and will also insure that the whole struct is aligned, too). Thus, 'p2-p1' will be greater than 1 and will indicate the alignment granularity (2 bytes, 4 bytes, etc.). Note that this code is essentially the same as the standard 'offsetof' macro. I expanded it out so that it's clearer how it works. The code is portable and should work on any ISO compiler.