0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

constexpr の 使い方 C/C++編

Last updated at Posted at 2025-07-31

C++N5008 Working Draft Programming Languages 7.7 constant expression
https://qiita.com/kaizen_nagoya/items/56797f546c2ca9dc65b7

C++には、constexprという便利な機能がある。

constant expressionという分野で、
expressionの結果がconstantになることがわかっている場合は、
コンパイル時にconstantにしておくというものである。

利点1 実行時間

コンパイル時にconstantになっていると、実行時に計算しないだけ、実行時間が短くすることができる。

利点2 ソフトウェアの大きさ

コンパイル時にconstantになっていると、計算処理の空間が必要なく、ソフトウェアの大きさを小さくすることができるかもしれない。

利点3 複雑なデータ構造の値を、プログラマが知らなくても、定数かどうかをコンパイル時に確かめることができる。

7.7 Constant expressions [expr.const]
constexpr int v = A(true).m; // OK, constructor call initializes m with the value 42
constexpr int w = A(false).m; // error: initializer for m is x, which is non-constant

構造体の要素の値が、定数になっているかどうかは、すべて覚えていない場合に、上記のようなプログラムを書いてみてコンパイルしてみればわかる。C++標準の例として示しているように、プログラマなら誰しも一度は描いて確かめたい感じ。

課題

課題は何があるか、いろいろコンパイルしてみて確かめ中です。
確かめるとよい事例があれば、お知らせください。

ISO/IEC 9899:202y (en) — N3550
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3550.pdf

C言語にもある。
ISO/IEC 9899:2024
https://www.iso.org/standard/82075.html
から採用。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?