c++ - 如何在 C++ 中编写简短的文字?

标签 c++ literals

非常基本的问题:如何在 C++ 中编写 short 文字?

我知道以下几点:

  • 2 是一个 int
  • 2U 是一个 unsigned int
  • 2Llong
  • 2LLlong long
  • 2.0f 是一个 float
  • 2.0 是一个 double
  • '\2' 是一个 char

但是我将如何编写 short 文字?我试过 2S 但这给出了编译器警告。

最佳答案

((short)2)

是的,严格来说,它不是一个简短的文字,更像是一个强制转换的整数,但行为是相同的,我认为没有直接的方法。

That's what I've been doing because I couldn't find anything about it. I would guess that the compiler would be smart enough to compile this as if it's a short literal (i.e. it wouldn't actually allocate an int and then cast it every time).

以下内容说明了您应该对此有多担心:

a = 2L;
b = 2.0;
c = (short)2;
d = '\2';

编译->反汇编->

movl    $2, _a
movl    $2, _b
movl    $2, _c
movl    $2, _d

关于c++ - 如何在 C++ 中编写简短的文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/208433/

相关文章:

literals - 此变量中的 Javascript 构造函数返回错误

c++ - 在构建时是否发生了特定于静态链接的任何事情

c++ - 如何让 ToolTip 出现在 float 的 CPaneDialog 的最前面?

c++ - 将 float 舍入为预定义点的规则网格

c++ - 包括文件冲突解决

javascript - 将 Prop 传递给 map 中的温度文字

带有效载荷的 C 双字面值 NaN

c++ - 从 argv[1] 获取数组的大小并用随机数填充它

c - c语言中 "literal" '\1'是什么定义?

css - 强制 lessc 按字面解释 @import