2012-10-05 13 views
13

Possible Duplicate:
Error “initializer element is not constant” when trying to initialize variable with const初期化子要素は、ここでは、私はジャバスクリプト/ PHP/Pythonのから来ていると、おそらく私は何かが欠けてるC

で一定していないコードは次のとおりです。

const int a = 50; 
const int c = 100; 
const int d = 100; 
int endX = c + a; 
int endY = d; 
int startX, startY, b; 

私は

を取得

ex1.4.c:6: error: initializer element is not constant
ex1.4.c:7: error: initializer element is not constant

誰か説明がありますか?

+1

外観は、この前に何度も頼まれました。尋ねる前にこのサイトを検索してください。 –

+0

私はあなたのコードをちゃんとコンパイルすることができます。どのコンパイラ/システムを使用していますか? – none

+0

@ gokcehan:万が一C++コンパイラを使用していますか? –

答えて

4

endXをグローバル変数として宣言している場合は、エラーになります。

なぜなら、グローバル変数はコンパイル時に初期化され、実行時に実行する必要がある操作としてendXを初期化しようとしているからです。

+4

-1。この答えは間違っています。実行時間の前にコンパイラがendXを計算するのを止めるものは何もありません。実際、g ++はこれをうれしくコンパイルします。それは、GCCが受け入れるものについて過度に気になるだけです。 – weberc2

2

ええ、あなたは何かを変数に初期化することはできません。コンパイラは初期化を行い、コンパイル時にはc+aという値を知らない。

int x = 1;型の初期化は問題ありません。コンパイラはオブジェクトコードのxのアドレスに1を置きます。

c+aに初期化するには、実行時に起動コードまたはコンストラクタC++にします。

0

Cプログラミング言語では、静的記憶期間を持つオブジェクトは、定数式(または定数式を含む集合体)で初期化する必要があります。 endXに静的記憶期間がある場合、その初期化子(c+a)は定数式ではありません(つまり、変換フェーズで式を評価することはできません)。

15

残念ながら、C constでは、変数は実際にはconstではありません。

下記はc99標準からの抽出物である。

6.6 Constant expressions

(7) More latitude is permitted for constant expressions in initializers. Such a constant expression shall be, or evaluate to, one of the following:

— an arithmetic constant expression,

— a null pointer constant,

— an address constant, or

— an address constant for an object type plus or minus an integer constant expression.

(8) An arithmetic constant expression shall have arithmetic type and shall only have operands that are integer constants, floating constants, enumeration constants, character constants, and sizeof expressions. Cast operators in an arithmetic constant expression shall only convert arithmetic types to arithmetic types, except as part of an operand to a sizeof operator whose result is an integer constant.

したがって、caは定数式ではなく、として使用することができない次のよう

6.4.4 Constants

Syntax

constant:

integer-constant  (e.g. 4, 42L) 
floating-constant  (e.g. 0.345, .7) 
enumeration-constant (stuff in enums) 
character-constant  (e.g. 'c', '\0') 

標準は定数式を定義して次のよう

6.7.8 Initialization

  1. All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

定数が定義されていますあなたのケースのイニシャライザ。

5

const式は、C++とは異なり、Cではコンパイル時定数である必要があります。したがって、c+aは定数として使用できません。 Cでこの問題を処理するための通常の方法ではなく、プリプロセッサを使用することです:この質問の右側のパネルで

#define A 50 
#define C 100 
#define D 100 
int endX = C + A; 
int endY = D; 
int startX, startY, b; 
+1

'c'と' a'がコンパイル時定数であれば、 'c + a'も同様です(そしてその式が割り当てられているもの)。 C++ではコンパイル時定数としてconst式を必要としません。それはC++は、 'const int + const int'はコンパイル時定数であるのに対して、Cはそれほどスマートではないことに気付くほどスマートです。 – weberc2

関連する問題