gpt4 book ai didi

c++ - 这个有界递归的程序是否有未定义的行为?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:33 25 4
gpt4 key购买 nike

我知道无限递归或迭代是未定义的行为,但有界不是。但是,这个程序段对于大多数输入都是错误的。它是否有未定义的行为,为什么或为什么不?如果它有未定义的行为,我是否可以进行一些修改以消除未定义的行为?

#include <cstdint>

using bigint = ::std::uint64_t;
constexpr const bigint add_val = 1442695040888963407;
constexpr const bigint mult_val = 6364136223846793005;

bigint compute(bigint t)
{
if (t > 1) {
return add_val + compute(t * mult_val);
} else {
return 1;
}
}

int main(int argc, char const * const argv[])
{
return compute(argc < 0 ? -argc : argc);
}

这基本上是使用递归循环遍历 linear congruential random number generator with a period of 2^64 的所有值所以它保证最终会达到 0 或 1。

我在问一个非常明确和具体的问题。根据 C++ 标准,这个任何人都可以编译和运行的完整程序是否会调用未定义的行为?

最佳答案

with thanks to 101010's standard link, I think the relevant phrase is

4.1 Implementation compliance [intro.compliance]

(2.1) - If a program contains no violations of the rules in this document, a conforming implementation shall, within its resource limits, accept and correctly execute that program.

Annex B (informative)

Implementation quantities [implimits]

主要解决编译器限制(最大符号长度、每行字符等),但语言听起来相关:

  1. Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where known. This documentation may cite fixed limits where they exist, say how to compute variable limits as a function of available resources, or say that fixed limits do not exist or are unknown.

  2. The limits may constrain quantities that include those described below or others ...

因此,该标准没有说明实现可能会限制哪些数量,也没有给出除它所描述的这些限制的最小值指南之外的任何内容。

如果您的编译器没有记录其堆栈深度限制,根据粗体句子,我猜它可能是不符合要求的,但是声明“堆栈深度受这些限制运行时属性” 可能就足够了..

Does this program that anybody can compile and run in its entirety invoke undefined behavior according to the C++ standard?

没有。但是,根据 4.1/2.1 的规定,允许编译失败或无法正确执行正确的程序。

关于c++ - 这个有界递归的程序是否有未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56811284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com