Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

Open
@Mq-b

Description

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

        AltStyle によって変換されたページ (->オリジナル) /