const keyword’ü bir değişkenin daha sonradan değiştirirmesini önlemek için kullanılır.

	const double PI = 3.14;
	PI = 5; // hata: const degiskenler degistirilemez

	const double e; // hata: constant degiskenler initialize edilmelidir.

	const int sayi = 5;
	int& r_sayi = sayi; // constant olan bir degisken non-constant bir referans ile gosterilemez.
	const int& r_sayi2 = sayi; // dogrusu

External

const global variable has internal linkage by default. If you want the variable to have external linkage, apply the extern keyword to the definition, and to all other declarations in other files:

//fileA.cpp
extern const int i = 42; // extern const definition

//fileB.cpp
extern const int i;  // declaration only. same as i in FileA

https://learn.microsoft.com/en-us/cpp/cpp/extern-cpp?view=msvc-170

TOP & LOW – LEVEL CONST

https://stackoverflow.com/questions/7914444/what-are-top-level-const-qualifiers

constexpr

Derleme zamanında çalışan(evaluate) ifadelere Constant expression denir.

The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const, it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike constconstexpr can also be applied to functions and class constructors. constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time.

constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations. And when a value is computed at compile time instead of run time, it helps your program run faster and use less memory.

To limit the complexity of compile-time constant computations, and their potential impacts on compilation time, the C++14 standard requires the types in constant expressions to be literal types.

devamı…

https://learn.microsoft.com/en-us/cpp/cpp/constexpr-cpp?view=msvc-170

const & constexpr

Both keywords can be used in the declaration of objects as well as functions. The basic difference when applied to objects is this:

  • const declares an object as constant. This implies a guarantee that once initialized, the value of that object won’t change, and the compiler can make use of this fact for optimizations. It also helps prevent the programmer from writing code that modifies objects that were not meant to be modified after initialization.
  • constexpr declares an object as fit for use in what the Standard calls constant expressions. But note that constexpr is not the only way to do this

devamı…

https://stackoverflow.com/questions/14116003/whats-the-difference-between-constexpr-and-const


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *