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

烈酒焚心 提交于 2019-12-12 09:24:49

问题


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);


来源:https://stackoverflow.com/questions/7711836/how-to-compute-the-word-size-of-your-computer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!