非常基本的问题:我怎么写 short 文字在C++?

我知道如下:

  • 2 是一个 int
  • 2U 是一个 unsigned int
  • 2L 是一个 long
  • 2LL 是一个 long long
  • 2.0f 是一个 float
  • 2.0 是一个 double
  • '\2' 是一个 char.

但我怎么会写 short 文字?我试过了 2S 但是,让一个编译器的警告。

有帮助吗?

解决方案

((short)2)

是啊,这不是严格短的文字,更多的铸-int,但该行为是相同的而且我觉得没有一个直接的方式这样做。

这就是我一直在做的因为我没找到任何事情。我猜那个编译器,将能够为汇编这个,如果它是一个简短的文字(即它不会实际分配一个int然后把它的每一次)。

以下说明有多少你应该担心这个:

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

编译>拆卸->

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

其他提示

C++11给你非常近你想要什么。 (搜索"用户定义的文本",以了解更多信息。)

#include <cstdint>

inline std::uint16_t operator "" _u(unsigned long long value)
{
    return static_cast<std::uint16_t>(value);
}

void func(std::uint32_t value); // 1
void func(std::uint16_t value); // 2

func(0x1234U); // calls 1
func(0x1234_u); // calls 2

// also
inline std::int16_t operator "" _s(unsigned long long value)
{
    return static_cast<std::int16_t>(value);
}

即使是作家的C99标准被抓住了这个。这是一个片段从丹尼*史密斯的共领域 stdint.h 执行:

/* 7.18.4.1  Macros for minimum-width integer constants

    Accoding to Douglas Gwyn <gwyn@arl.mil>:
    "This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC
    9899:1999 as initially published, the expansion was required
    to be an integer constant of precisely matching type, which
    is impossible to accomplish for the shorter types on most
    platforms, because C99 provides no standard way to designate
    an integer constant with width less than that of type int.
    TC1 changed this to require just an integer constant
    *expression* with *promoted* type."
*/

如果你使用微软视C++、有文字后适用于每一整数类型:

auto var1 = 10i8;  // char
auto var2 = 10ui8; // unsigned char

auto var3 = 10i16;  // short
auto var4 = 10ui16; // unsigned short

auto var5 = 10i32;  // int
auto var6 = 10ui32; // unsigned int

auto var7 = 10i64;  // long long
auto var8 = 10ui64; // unsigned long long

注意,这些都是 非标准的扩展不是便携式的.事实上,我甚至不能找到任何信息,这些后缀在MSDN。

你也可以使用伪构造的语法。

short(2)

我觉得它更加可读于铸造。

据我所知,你不要,没有这样的后缀。最编译器会发出警告,如果一个整数字太大,以适应在任何可变你想把它储存在,虽然。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top