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.