How to use constexpr to set a static value at compilation time in C++

1 Answer

0 votes
// constexpr is a value that will not change (static) and is set at the compilation time

#include <iostream>
 
class Example {
    public:
        static constexpr int num = 34;
        Example() {};
};
     

int main() {
    Example obj;
     
    std::cout << obj.num << "\n";
     
    int x = obj.num + 52;
    std::cout << x;
    
    // obj.num = 100; // error: assignment of read-only variable 'Example::num'
}
   
   
   
   
/*
run:
   
34
86
   
*/

 



answered Sep 15, 2024 by avibootz

Related questions

1 answer 193 views
1 answer 182 views
1 answer 185 views
1 answer 209 views
1 answer 186 views
1 answer 202 views
...