How to compute the word size of your computer in C

2020-07-30 03:37发布

问题:

This question already has answers here:
Closed 8 years ago.

Possible Duplicate:
Determine word size of my processor

It is One Interview question today. But I didn't know ...


I think the interviewer meaned the word size of cpu.


I find an answer like this:

int cpu_bits(void *dummy1, void *dummy2) 
{ 
 long offset = (long)&dummy2 - (long)&dummy1; 
 int ret = 0; 
 if (8 == offset) 
     ret = 64; 
 else if (4 == offset) 
     ret = 32; 
 else if (2 == offset) 
     ret = 16; 
 else if (1 == offset) 
     ret = 8; 
 else 
     ret = -1; 
 return ret;  
} 

int main() 
{ 
 printf("%d\n", cpu_bits(NULL, NULL)); 
 return 0; 
} 

The result seems to be right, Do you think so ?

回答1:

Short answer: the standard does not define a data type that is guaranteed to correspond to the word size of the underlying architecture, and what "word size" means on modern CPU's is quite a vague thing: Word Size versus Address Size.

With current processors having compatibility modes, registers of a different size, advanced addressing modes and instructions suited for data of various widths, talking of a general "word size" is imprecise, to say the least.

I suppose the interviewer is still living in the 90's and remembers the dubiously called WORD and DWORD types that were introduced by WinAPI when most computers were still 16-bit.



回答2:

I think they were expecting something like this:

printf("%d\n", (int)sizeof(int) * CHAR_BIT);