这里的'L'有什么意义?

时间:2013-09-29 00:50:38

标签: 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'似乎运行代码就好了。

2 个答案:

答案 0 :(得分:11)

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

因此,您不会冒险将值本身截断;但是:

  1. 你确实对文字的类型有一定程度的不确定性(32768可能是intlong,具体取决于平台/编译器);
  2. 您可能无意中为您的特定表达式获取了错误类型的文字。
  3. 因此,您需要在要确保文字类型为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!
      

      32767int字面值(因为它足够小以适合int),aint,结果将是int,即使您要分配给long。如果a可能大到足以使计算失败,则可能会出现问题;通过指定long字面值,您可以保证执行long乘法。

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

      (对于除法和FP文字,这个问题实际上 way 更频繁,通常你必须指定doublefloat文字来获得预期的“真正的划分”行为)

      正如 @chris 所暗示的那样,当进行“大”位移时会出现更频繁的情况(同样类型),例如:

      long long mask=1<<53;
      

      提出了与上述相同的问题:1int53int,计算将使用int执行,结果溢出(尽管在这种特殊情况下,任何体面的编译器都会发出警告);这里正确的形式是:

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

    来到您的特定代码:将L带走是没有风险的;由于number已经是long2无论如何都会在模数中被提升为long(根据“通常的算术转换”,§5¶10,和§4.5),所以这里L没有区别。

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


    1.   

      整数文字的类型是表6中相应列表的第一个,其值可以是   表示。   table from the C++11 standard describing the type to be used for integer literals

答案 1 :(得分:0)

在这种情况下,没有必要。

L表示长值,这意味着它会保留更多空间,只需计算超出正常整数的范围。

相关问题