Answer to Question 2.8

/* Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
/* The C++ Answer Book */
/* Tony Hansen */
/* All rights reserved. */
		3b20

char		0,255
short		-32768,32767
int		-2147483648,2147483647
long		-2147483648,2147483647
float
double
unsigned
char *
int *
void *

*******************************************************************
//: find the alignment restrictions on
// addresses of various types
#include <stream.h>
#include <setjmp.h>

jmp_buf jmpenv;

#include "2_8a4.c"	/* EXPAND */

#include <tstbadalign.h>

int main(int, char**)
{
#include "2_8a1.c"		/* EXPAND4 */

#include "2_8a3.c"		/* EXPAND4 */

    tstbadalignments(char,	"char");
    tstbadalignments(short,	"short");
    tstbadalignments(int,	"int");
    tstbadalignments(long,	"long");
    tstbadalignments(float,	"float");
    tstbadalignments(double,	"double");
    tstbadalignments(char*,	"char*");
    tstbadalignments(int*,	"int*");
    tstbadalignments(void*,	"void*");

    return 0;
}

//: 2_8a4.c
// print a message each time a signal is caught
#include <signal.h>

void trapsig(int signo)
{
    signal(signo, trapsig);	// reset signal
    cout << ", signal " << signo << " caught";
    longjmp(jmpenv, 1);
}

//:2_8a1.c
union foo
    {
    double f;	// force maximal alignment
    long l;
    char a[  sizeof(double) >   sizeof(long) ?
	   2*sizeof(double) : 2*sizeof(long)];
    } foovar;

//:2_8a3.c
// initialize the signal catcher
(void) signal(SIGEMT, trapsig);


//: <tstbadalign.h>
// this macro will test an assignment
// to an address of each possible offset
// for a given type
#define tstbadalignments(type,typestr)		\
    {						\
    type *ip;					\
    type ivar;					\
    int offset;					\
    cout << "Type = " << typestr << "\n";	\
    for (offset = 0;				\
	 offset < sizeof(type);			\
	 offset++)				\
	{					\
	cout << "\toffset = " << offset;	\
	ip = (type *)&foovar.a[offset];		\
	if (!setjmp(jmpenv))			\
	    ivar = *ip;				\
	cout << "\n";				\
	}					\
    }

*******************************************************************
#include <stdio.h>
#include <values.h>

int main(int, char**)
{
    printf("maxshort=%d\n", MAXSHORT);
    printf("minshort=%d\n", HIBITS);
    printf("maxlong=%d\n", MAXLONG);
    printf("minlong=%d\n", HIBITL);
    printf("maxshort+1=%d\n", MAXSHORT + 1);
    printf("maxlong+1=%d\n", MAXLONG + 1);
    return 0;
}
Menu of Chapter 2 Answers
Answer to Question 2.9