简体   繁体   English

在 C++ 中声明 INFINITY 的正确方法是什么?

[英]What is the right way to declare the INFINITY in c++?

const int INFINITY = INT_MAX;

gives me the给我

expected an identifier期望一个标识符

error.错误。 Could you please tell what am I missing?你能告诉我我错过了什么吗? I tried to include <cmath> but it did not help.我试图包括<cmath>但它没有帮助。

The problem is that INFINITY is either a macro from the <cmath> header.问题是INFINITY要么是来自<cmath>标头的 This is expanded to an implementation-defined value by the preprocessor before the actual compilation.在实际编译之前,预处理器将其扩展为实现定义的值。 In the case of GCC (check with g++ -E ), the expression (__builtin_inff ()) takes the place of INFINITY , which clearly not a valid identifier.在 GCC 的情况下(用g++ -E检查),表达式(__builtin_inff ())代替了INFINITY ,这显然不是一个有效的标识符。

A quick fix is to give your constant a different name, such that it is not reserved by the implementation (is not a name of a standard macro):一个快速的解决方法是给你的常量一个不同的名字,这样它就不会被实现保留(不是标准宏的名字):

const int infinity = INT_MAX;

But, when it comes to the title of the question:但是,当谈到问题的标题时:

What is the right way to declare the INFINITY in c++?在 C++ 中声明 INFINITY 的正确方法是什么?

refer to this Q&A that suggests this C++ standard library equivalent:请参阅此问答,其中建议使用此 C++ 标准库等效项:

#include <limits>

const int infinity = std::numeric_limits<int>::max();

Note that integers do not have reserved infinity (Inf), or not a number (NaN) and operations that result in a value out of int 's range will (still) overflow, as opposed to operations with IEEE floating-point numbers, which according to this Q&A , don't overflow and result in Inf .请注意,整数没有保留的无穷大(Inf) 或不是数字(NaN) 并且导致值超出int范围的操作将(仍然)溢出,这与使用 IEEE 浮点数的操作相反,后者根据这个问答,不要溢出并导致Inf

INT_MAX is the C way. INT_MAX 是 C 方式。 You should use the following in C++ :-您应该在 C++ 中使用以下内容:-

#include <limits>

int infinity = std::numeric_limits<int>::max();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM