Sandip
Sandip

Reputation: 775

Primitive data type in C to represent the WORD size of a CPU-arch

I observed that size of long is always equal to the WORD size of any given CPU architecture. Is it true for all architectures? I am looking for a portable way to represent a WORD sized variable in C.

Upvotes: 1

Views: 714

Answers (6)

Grissiom
Grissiom

Reputation: 12053

Things will get more complicated in embedded world. ASAIK, C51 is 8bit processor but in Keil C for c51, long have 4 bytes. I think it's compiler dependent.

Upvotes: 1

Daniel Newby
Daniel Newby

Reputation: 2432

No. In fact, the scalar and vector units often have different word sizes. And then there are string instructions and built-in DMA controllers with oddball capabilities.

If you want to copy data fast, memcpy from the platform's standard C library is usually the fastest.

Upvotes: 3

strager
strager

Reputation: 90022

C doesn't deal with instructions. In C99, you can copy any size struct using an single assignment:

struct huge { int data[1 << 20]; };
struct huge a, b;
a = b;

With a smart compiler, this should generate the fastest (single-threaded, though in the future hopefully multi-threaded) code to perform the copy.

You can use the int_fast8_t type if you want the "fastest possible" integer type as defined by the vendor. This will likely correspond with the word size, but it's certainly not guaranteed to even be single-instruction-writable.

I think your best option would be to default to one type (e.g. int) and use the C preprocessor to optimize for certain CPU's.

Upvotes: 3

osgx
osgx

Reputation: 94235

No, standard have no such type (with maximize memory throughput).

But it states that int must be fastest type for the processor for doing ALU operations on it.

Upvotes: 1

user180247
user180247

Reputation:

I think the nearest answers you'll get are...

  • int and unsigned int often (but not always) match the register width of the machine.
  • there's a type which is an integer-the-same-size-as-a-pointer, spelled intptr_t and available from stddef.h IIRC. This should obviously match the address-width for your architecture, though I don't know that there's any guarantee.

However, there often really isn't a single word-size for the architecture - there can be registers with different widths (e.g. the "normal" vs. MMX registers in Intel x86), the register width often doesn't match the bus width, addresses and data may be different widths and so on.

Upvotes: 1

Dean Harding
Dean Harding

Reputation: 72658

Under Windows, sizeof(long) is 4, even on 64-bit versions of Windows.

Upvotes: 2

Related Questions