How do I write a short literal in C++?

Very basic question: how do I write a short literal in C++?

I know the following:

  • 2 is an int
  • 2U is an unsigned int
  • 2L is a long
  • 2LL is a long long
  • 2.0f is a float
  • 2.0 is a double
  • '2' is a char .
  • But how would I write a short literal? I tried 2S but that gives a compiler warning.


    ((short)2)
    

    Yeah, it's not strictly a short literal, more of a casted-int, but the behaviour is the same and I think there isn't a direct way of doing it.

    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 (ie it wouldn't actually allocate an int and then cast it every time).

    The following illustrates how much you should worry about this:

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

    Compile -> disassemble ->

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

    C++11 gives you pretty close to what you want. (Search for "user-defined literals" to learn more.)

    #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);
    }
    

    Even the writers of the C99 standard got caught out by this. This is a snippet from Danny Smith's public domain stdint.h implementation:

    /* 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."
    */
    
    链接地址: http://www.djcxy.com/p/58324.html

    上一篇: 为什么c / c ++浮点类型如此奇怪地命名?

    下一篇: 我如何在C ++中编写简短的文字?