How to compute the word size of your computer in C

2020-07-30 03:45发布

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 ?

2条回答
Animai°情兽
2楼-- · 2020-07-30 04:08

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.

查看更多
Anthone
3楼-- · 2020-07-30 04:15

I think they were expecting something like this:

printf("%d\n", (int)sizeof(int) * CHAR_BIT);
查看更多
登录 后发表回答