constexpr and its difference between define:
Def: constexpr is a keyword that specifies that an expression can be evaluated at compile time
Features:
-
- the function will be evaluated at compile time
-
- must has a single return statement and no side effects
-
- must be executed with constant arguments
constexpr int factorial(int n){
return (n <= 1) ? 1 : n * factorial(n-1);
}
constexpr int x = factorial(5); // x is evaluated at compile time to be 120
Note that constexpr functions can also be used in non-constant expressions, in which case they will be evaluated at runtime just like regular functions.
Here is an example of constexpr in both constant and non-constant case:
-
#include <iostream> constexpr int factorial(int n) { return n <= 1 ? 1 : n * factorial(n - 1); } int main() { // Constant expression constexpr int x = factorial(5); // x = 120 will be determined in compile time std::cout << "Factorial of 5 is " << x << std::endl; // 120 // Non-constant expression int y = 6; int z = factorial(y); // z is determind at run time, like a regular func std::cout << "Factorial of " << y << " is " << z << std::endl; // 720 return 0; }
Difference:
Both of them can define constant. However, constexpr is a compile-time constatns, meaning that their values must be determinable at compile time. Macro definition is a simple text replacements without type information and cannot be checked at compile time. Using macro definitions to define constants can therefore lead to type errors or incorrect values that may only be discovered at runtime.
In a nutshell, constexpr constants are typically more type-safe and can provide better compile-time checks, while macro definitions can have type issues and may be difficult to catch at compile time.