Hampir semua jawaban lain benar, tetapi salah satu aspeknya terlewat: Saat Anda menggunakan ekstra constpada parameter dalam deklarasi fungsi, compiler pada dasarnya akan mengabaikannya. Untuk sesaat, mari kita abaikan kompleksitas contoh Anda sebagai penunjuk dan cukup gunakan int.
void foo(const int x);
mendeklarasikan fungsi yang sama seperti
void foo(int x);
Hanya dalam definisi fungsinya adalah ekstra constbermakna:
void foo(const int x) {
// do something with x here, but you cannot change it
}
Definisi ini kompatibel dengan salah satu deklarasi di atas. Penelepon tidak peduli bahwa xadalahconst -yang 's detail implementasi yang tidak relevan di situs panggilan.
Jika Anda memiliki constpenunjuk ke constdata, aturan yang sama berlaku:
// these declarations are equivalent
void print_string(const char * const the_string);
void print_string(const char * the_string);
// In this definition, you cannot change the value of the pointer within the
// body of the function. It's essentially a const local variable.
void print_string(const char * const the_string) {
cout << the_string << endl;
the_string = nullptr; // COMPILER ERROR HERE
}
// In this definition, you can change the value of the pointer (but you
// still can't change the data it's pointed to). And even if you change
// the_string, that has no effect outside this function.
void print_string(const char * the_string) {
cout << the_string << endl;
the_string = nullptr; // OK, but not observable outside this func
}
Beberapa programmer C ++ repot-repot membuat parameter const, bahkan ketika mereka bisa, terlepas dari apakah parameter tersebut adalah pointer.