[net.lang.c] what about alignment problems?

kpmartin@watmath.UUCP (Kevin Martin) (07/12/84)

After all, not everyone has ints, longs, and pointers all of the same size
and alignment...

There is currently no way in C to get the alignment required by a type.
This makes writing a special-purpose storage allocator difficult. It also
means that it is difficult to write a varargs function cleanly (since
stepping though the args required aligning the pointer to the next boundary
appropriate for the next type).

Would it not be useful to have an 'alignof' operator, with the same usage
as 'sizeof', but which returns the byte alignment required by the given
type or expression?

About the only reason against this is the 'yet *another* keyword' problem.

jim@ism780b.UUCP (08/01/84)

#R:watmath:-831800:ism780b:25500006:000:1184
ism780b!jim    Jul 14 12:38:00 1984

Try

struct _aschar   {char    _cchar;   char   _achar;};
struct _asshort  {char    _cshort;  short  _ashort;};
struct _asint    {char    _cint;    int    _aint;};
struct _aslong   {char    _clong;   long   _along;};
struct _asfloat  {char    _cfloat;  float  _afloat;};
struct _asdouble {char    _cdouble; double _adouble;};
struct _asptr    {char    _cptr;    char * _aptr;};
#define QUOTE(x)x
#define alignof(t) ( (int)&((struct QUOTE(_as)t *)0)->QUOTE(_a)t )

main(){
	printf("%d %d %d %d %d %d %d\n",
	    alignof(char), alignof(short), alignof(int), alignof(long),
	    alignof(float), alignof(double), alignof(ptr));
}

Admittedly, ptr is a hack and assumes all pointers have the same alignment
requirement (more likely than that they all have the same size), and it
would be a lot cleaner if alignof were in the language.

While we are at it, what would be even more useful would be typeof,
especially if it could be used in declarations, so you could do

	/* declaration with initialization */
	typeof(foo) foosave = foo;

or

#define acopyof(foo) ( *(typeof(foo) *) \
	memcpy(malloc(sizeof(foo)), (char *)&(foo), sizeof(foo)) )

-- Jim Balter, INTERACTIVE Systems (ima!jim)