12,982
回編集
(→概要) |
|||
29行目: | 29行目: | ||
<br><br> | <br><br> | ||
== | == constexpr変数 == | ||
constexpr変数は、<code>#define</code>等で作成するようなコンパイル時定数を作るためのキーワードである。<br> | |||
<br> | <br> | ||
constとは、「この変数は変更しないため、変更しようとする場合はコンパイルエラーにする」という合図である。<br> | |||
constexprとは、「この変数の値はコンパイル時に確定するため、確定しない場合はコンパイルエラーにする」という合図である。<br> | |||
<br> | <br> | ||
また、constexpr変数は、const変数としても扱われる。<br> | また、constexpr変数は、const変数としても扱われる。<br> | ||
<br> | <br> | ||
コンパイラは、constexpr変数の値をコンパイル時に計算しようとする。<br> | |||
もし、計算できなければ、コンパイルエラーを出力する。<br> | |||
<br> | <br> | ||
どの操作がコンパイル時に計算可能かは、関数にconstexprキーワードが付いているかどうかで判断される。(後述のセクションで記載する)<br> | どの操作がコンパイル時に計算可能かは、関数にconstexprキーワードが付いているかどうかで判断される。(後述のセクションで記載する)<br> | ||
< | <br> | ||
以下の例では、1行目でbufSizeを9に初期化している。<br> | |||
この演算はコンパイル時に行うため、constexpr変数を初期値9で宣言することにより、ROM上に配置される。<br> | |||
<syntaxhighlight lang="c++"> | |||
constexpr unsigned int bufSize = sizeof("abc def¥n"); | |||
static_assert(bufSize == 9, "bufSize is not 9"); | |||
char buf[bufSize] = {0}; | |||
fgets(buf, sizeof(buf), stdin); | |||
const int a = atoi(strtok(buf," ¥n")); | |||
const int b = atoi(strtok(nullptr," ¥n")); | |||
std::cout << (a + b) / 2 << std::endl; | |||
</syntaxhighlight> | |||
<br> | |||
以下の例では、列挙型Colorはint32_t型であり、3つの値をとる。<br> | |||
static宣言されたColor型の配列は、constexpr指定子が付加されて、ROM上に配置される。<br> | |||
<syntaxhighlight lang="c++"> | |||
typedef enum Color : int32_t | |||
{ | |||
Red = 0, | |||
Yellow, | |||
Blue | |||
} Color; | |||
constexpr static Color colors[] = | |||
{ | |||
Color::Red, | |||
Color::Yellow, | |||
Color::Blue | |||
}; | |||
</syntaxhighlight> | |||
<br> | |||
以下のサンプルコードでは、<u>標準入力から受け取る</u>操作がコンパイル時に行えないため、コンパイルエラーとなる。<br> | |||
<syntaxhighlight lang="c++"> | |||
#include <iostream> | #include <iostream> | ||
70行目: | 105行目: | ||
return 0; | return 0; | ||
} | } | ||
</ | </syntaxhighlight> | ||
<br><br> | <br><br> | ||