开发者

How to compute the word size of your computer in C? [duplicate]

This question already has answers here: Closed 11 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 ?


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.


I think they were expecting something like this:

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜