开发者

How to predict the size of a specific data type in C?

I know that size of data types in C aren't fixed for all Architects.

But for a fixed CPU architect,how can I predict the size of sizeof(unsigned short) ?开发者_StackOverflow中文版

By predict I mean not by test(printf("%d",sizeof(unsigned short));)


Read your compiler documentation.


You cannot "predict" the size in bytes, but you can "predict" the range:

#include <limits.h>

#if USHRT_MAX < 65535
/* less than the minimum guaranteed by the Standard: will never happen */
#elif USHRT_MAX == 65535
/* minimum guaranteed by the Standard: 2 8-bit bytes */
#elif USHRT_MAX <= 420042
/* a little more room than guaranteed by the Standard */
#elif USHRT_MAX <= 2000000000
/* a lot more room than guaranteed by the Standard */
#else
/* 640K ought to be enough for anybody */
#endif


If you want to have consistent, predictable sizes for your data types, you shouldn't be using short, int, long, etc. The C99 standard introduced standard types to specify exact-width integers. Include the stdint.h header to get access to types like uint16_t and int64_t for 16-bit unsigned and 64-bit signed integers, respectively, regardless of what architecture you're running on.


Use uint16_t instead - that is guarranteed by stdint.h to be exactly 16-bits or to prevent compilation if no 16-bit value is possible on the architecture.

If you just want to check, consider using C_ASSERT(sizeof(T) == 2) - this will cause a compile-time error if T is not 2 bytes long. That way you can know that T is 2 bytes long in every compiled binary (since if it wasn't for some strange compiler reason, the build would have failed).


you either read the compiler documentation or write a program you can run on the architecture / compiler you want to gather information about:

/* $Id: sizeof.c,v 1.1 2009/07/05 10:37:54 sms Exp $
 * www.pccl.demon.co.uk
 * Program to display data sizes. */

#include    <stdio.h>
#include    <time.h>
#include    <sys/types.h>

#define printsize(x)    printf ("sizeof (" #x ")    = %d\n", sizeof (x))

main ()
{
    printf ("\nC\n");
    printsize (char);
    printsize (double);
    printsize (float);
    printsize (int);
    printsize (long);
    printsize (long long);
    printsize (short);
    printsize (void *);

    printf("\n");
    printsize (clock_t);
    printsize (gid_t);
    printsize (pid_t);
    printsize (size_t);
    printsize (ssize_t);
    printsize (time_t);
    printsize (uid_t);
}

http://www.pccl.demon.co.uk/C/sizeof.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜