c++ - 'L' 在这里有什么意义?

标签 c++

//Using the if-else
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main() {
  long number = 0;                  // Store input here
  cout << "Enter an integer less than 2 billion: ";
  cin >> number;
  cout << endl;

  if(number % 2L == 0)              // Test remainder after division by 2
    cout << "Your number is even."  // Here if remainder is 0
         << endl;
  else
    cout << "Your number is odd."   // Here if remainder is 1
         << endl;
  return 0;
}

这里,在第一个'if'条件下,为什么他们在2之后有'L'?去掉“L”似乎可以很好地运行代码。

最佳答案

L 后缀用于表示数字文字是 long int 类型。通常,如果您只是将值分配给变量,则没有必要,因为对于 C++11 §2.14.2 ¶2(尤其是表 6),没有后缀的十进制整数文字将是第一种类型可以在 intlong intlong long int 之间表示。1

因此,您不要冒险让值本身被截断;但是:

  1. 您确实对文字的类型有一定程度的不确定性(32768 可能是 intlong,具体取决于平台/编译器);
  2. 您可能会无意中为您的特定表达式获取错误类型的文字。

因此,您需要在上下文中指定 L 以确保文字类型为 long(或更大);我想到了两个重要的案例:

  • 解决过载问题;如果您有两个函数重载,一个用于 int,一个用于 long,并且您希望确保调用 long 一个如果您要传递一个小数字,则必须使用 long 文字;

    void foo(int);
    void foo(long);
    
    foo(1);      // <-- will call the first overload
    foo(1L);     // <-- will call the second overload
    foo(32768);  // <-- may call the first or the second overload, depending
                 //     from the specific platform
    foo(32768L); // <-- will call the second overload
    
  • 但最重要的是:在做算术时避免意外;如果你执行例如像这样的乘法:

    int a;
    ...
    long v=32767*a; // don't let the "long" fool you - 32767*a is evaluated as an int!
    

    32767 是一个 int 文字(因为它足够小以适合 int),a 是一个int,结果将是一个 int,即使您分配给一个 long。如果 a 大到足以溢出您的计算,这可能是个问题;通过指定一个 long 字面量,您保证您将执行一个 long 乘法。

    long v=32767L*a; // now we are doing all the math with longs
    

    (这个问题实际上方式在除法和 FP 字面量中更常见,通常你必须指定 doublefloat 字面量才能得到预期的“真正的 split ”行为)

    正如 @chris 所建议的,在进行“大”位移位时会出现一种更频繁的情况(同类),例如:

    long long mask=1<<53;
    

    呈现与上面相同的问题:1 是一个int53 是一个int,计算将使用 int 执行,导致溢出(尽管在这种特殊情况下任何体面的编译器都会发出警告);这里正确的形式是:

    long long mask=1LL<<53; // LL is the suffix for long long
    

针对您的特定代码:去掉 L 没有风险;因为 number 已经是一个 long,所以 2 在进行模运算时无论如何都会被提升为 long(根据“通常的算术转换”,§5 ¶10 和 §4.5),所以这里 L 没有区别。

尽管如此,在许多情况下,保留“预期类型”的字面量并不是一个坏主意:它保证,即使其他操作数的类型由于某种原因更改为更窄的类型,计算仍然会以预期的方式完成(不是模数,它会有任何不同)。


  1. The type of an integer literal is the first of the corresponding list in Table 6 in which its value can be represented. table from the C++11 standard describing the type to be used for integer literals

关于c++ - 'L' 在这里有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19073325/

相关文章:

c++ - 如何在 mac osx 中隐藏终端窗口?

C++ tcp socket连接重试方法

c++ - 如何使用 Boost d_ary_heap?

c++ - 共享内存分配 > 2GB(需要链接到 VB6 使用的 32 位 DLL)

c++ - 执行 C++ 程序的命令行参数

c++ - 使用 OpenCV 在 VS2005 中出现堆损坏错误?

C++ unordered_map - 没有可行的重载运算符[]

c++ - 在 POSIX 上生成随机 double 的最佳方法是什么?

c++ - 链接器错误 - 未定义对 "namespace::class::function()"的引用

c++ - 为什么在这种情况下 g++ 不遵守一项定义规则 (ODR)? 。