defining typed constant numbers in C/C++

丶灬走出姿态 提交于 2019-12-11 01:03:39

问题


In C/C++, is there a difference between saying (1U) vs. ((unsigned int)1) ? I prefer the second one, but I am concerned that the second one may be type-cast at run time (i.e. extra cpu cycles), whereas the first one gets the correct type at compilation. Thanks.


回答1:


They're not equivalent. 1U is valid in #if preprocessing directives. (unsigned int)1 is a syntax error at the preprocessor level. You could however make it (unsigned)+1 and it would be valid in the preprocessor, but only because of an obscure rule few people know..




回答2:


I think you have it right. (1U) I suspect will be recognised by the compiler's lexical analysis as "unsigned" while (unsigned int)1 will be a runtime operation. As the comments say, chances are it will be optimised out for you anyway.

As a general rule, don't try to out think the compiler. Do what looks most readable to you and worry about performance optimization once it becomes clear you have a problem. I can guarantee* this will never actually cause you a problem.

*guarantee void on days ending with a Y.




回答3:


11 characters. Otherwise, they are equivalent.



来源:https://stackoverflow.com/questions/9170683/defining-typed-constant-numbers-in-c-c

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