Skip to content

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

Open
@Mq-b

Description

@Mq-b
Contributor
  • 文件路径: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测试

Activity

changed the title [-]编译器扩展,而非是新编译器优化的问题,解释有误[/-] [+]`constexpr` 一节中,是编译器扩展导致,而非是**新编译器优化**的问题,解释有误[/+] on May 22, 2024
changed the title [-]`constexpr` 一节中,是编译器扩展导致,而非是**新编译器优化**的问题,解释有误[/-] [+]`constexpr` 一节中,是编译器扩展导致,而非是新编译器优化的问题,解释有误[/+] on May 22, 2024
heckerpowered

heckerpowered commented on Jul 16, 2024

@heckerpowered

卢瑟,链接都给错了😡

mobs001

mobs001 commented on Dec 20, 2024

@mobs001

这个书目前是什么情况呀,几乎隔段就是错误,好像一直没有维护,在线版本完全没有修订和更新,完全缺乏可读性了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @heckerpowered@Mq-b@mobs001

      Issue actions

        `constexpr` 一节中,是编译器扩展导致,而非是新编译器优化的问题,解释有误 · Issue #289 · changkun/modern-cpp-tutorial