Are long-suffix and unsigned-suffix needed when declaring long literals in C++?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-21 20:59:05

问题


I have some ancient memories of writing C code like:

long value = 0;

in the bad old Win16 days and ending up with value being only half-initialized: i.e. the lower 16 bits were 0 and the upper 16 bits were whatever random bits were at that location in memory. As such, I became conditioned to write:

long value = 0L;

Is this still required in this day-and-age under C99 and/or C++? I know that ILP32 specifies that int and long are both 32-bit, but suppose we're using, say, LP64 where ints are 32-bits and longs are 64-bits. Are the suffixes required or will the modern forms of C and C++ implicitly extend literals to the length of the variable they're being assigned to?

How about unsigned values? I.e. is this required?

unsigned long value = 0UL;

回答1:


They are not required in the examples you gave. However, they may be needed in some somewhat recondite circumstances. For example, the following may produce different values:

sizeof(1)
sizeof(1L)



回答2:


No this should not be required any more. The behavior you are describing, if visible in the program and not just the debugger, is a bug.




回答3:


Since you are presuming a 32-bit compiler, you may not need L as you did when using a 16-bit compiler, but you could need LL, e.g.:

long long ll;
ll = 1<<32;

gcc -std=c99 warns "left shift count >= width of type." Instead, you'd want:

ll = 1LL<<32;

See also https://stackoverflow.com/a/8108658/782738, for C++11 and C99 standard references.




回答4:


But this notation is required for wchar_t strings, like

L"I am a wchar_t string."

and for long long integers, too...

I guess this is something that should be removed, it isn't useful (the type is declared with its name and not with some suffix), but still supported in C++11.

Hm.



来源:https://stackoverflow.com/questions/975942/are-long-suffix-and-unsigned-suffix-needed-when-declaring-long-literals-in-c

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