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 189 views
1 answer 172 views
1 answer 180 views
1 answer 204 views
1 answer 181 views
1 answer 197 views
...