Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

constexpr 一节中,是编译器扩展导致,而非是新编译器优化的问题,解释有误 #289

Open
Mq-b opened this issue May 22, 2024 · 0 comments · May be fixed by #290
Open

Comments

@Mq-b
Copy link
Contributor

Mq-b commented May 22, 2024

  • 文件路径:book/zh-cn/02-usability.md

web 端

原文:

#include <iostream>
#define LEN 10

int len_foo() {
   int i = 2;
   return i;
}
constexpr int len_foo_constexpr() {
   return 5;
}

constexpr int fibonacci(const int n) {
   return n == 1 || n == 2 ? 1 : fibonacci(n-1)+fibonacci(n-2);
}

int main() {
   char arr_1[10];                      // 合法
   char arr_2[LEN];                     // 合法

   int len = 10;
   // char arr_3[len];                  // 非法

   const int len_2 = len + 1;
   constexpr int len_2_constexpr = 1 + 2 + 3;
   // char arr_4[len_2];                // 非法
   char arr_4[len_2_constexpr];         // 合法

   // char arr_5[len_foo()+5];          // 非法
   char arr_6[len_foo_constexpr() + 1]; // 合法

   std::cout << fibonacci(10) << std::endl;
   // 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
   std::cout << fibonacci(10) << std::endl;
   return 0;
}

(省略代码解释...)

注意,现在大部分编译器其实都带有自身编译优化,很多非法行为在编译器优化的加持下会变得合法,若需重现编译报错的现象需要使用老版本的编译器。

这段描述基本可以说是在胡说八道。

  1. 很多非法行为在编译器优化的加持下会变得合法” 这里和优化毫无关系,且这段话非常不好。之所以以上代码可以在一些编译器通过编译,那是因为 gccclang 等编译器默认情况下部分支持了 C 语言的特性:“变长数组”,才让定义的数组时,长度可以是非常量表达式。测试
  2. 若需重现编译报错的现象需要使用老版本的编译器。”,这也是经典的错误想法,传播极其之远。这里如果想要重现编译报错,那就是添加编译选项,禁用扩展:-pedantic-errors测试
@Mq-b Mq-b changed the title 编译器扩展,而非是新编译器优化的问题,解释有误 constexpr 一节中,是编译器扩展导致,而非是**新编译器优化**的问题,解释有误 May 22, 2024
@Mq-b Mq-b changed the title constexpr 一节中,是编译器扩展导致,而非是**新编译器优化**的问题,解释有误 constexpr 一节中,是编译器扩展导致,而非是新编译器优化的问题,解释有误 May 22, 2024
Mq-b added a commit to Mq-b/modern-cpp-tutorial that referenced this issue May 25, 2024
@Mq-b Mq-b linked a pull request May 25, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant