next up previous contents index
Nächste Seite: 3. Operatoren Aufwärts: 2.2 Konstanten Vorherige Seite: 2.2.5 Symbolische Konstanten (Macros)   Inhalt   Index


2.2.6 Konstante mit Variablennamen

Wird eine Variablenvereinbarung zusätzlich mit dem Schlüsselwort const gekennzeichnet, so kann diese Variable nur im Vereinbarungsteil initialisiert werden und danach nie wieder, d.h., sie wirkt als Konstante. (siehe Ex226.cc)

//	Constants and variables

#include <iostream.h>

main()
{
 const int  N = 5;     // The only initialization of constant
       int  i, j = 5;  // First    initialization of variable
       
 cout << "Hello World\n";
 
 i = j + N;
 
 cout << endl << i << " " << j << " " << N << endl;
}

Unterschied:
#define N 5
Es wird kein Speicherplatz für N benötigt, da N im gesamten Quelltext durch 5 ersetzt wird.


const int N = 5;
Variable N wird gespeichert, das Programm arbeitet mit ihr.




Gundolf Haase 2004-01-15