CS253

CS253: Software Development with C++

Spring 2018

Constexpr

See this page as a slide show

Constexpr

CS253 Constexpr

constexpr

Examples

constexpr auto pi = 3.14159;
cout << pi << '\n';
3.14159
constexpr double avo=6.022e23;
avo = 1.234;
cout << avo;
c.cc: In function 'int main()':
c.cc:2:7: error: assignment of read-only variable 'avo'

Trying to cheat

Let’s try to fool constexpr:

constexpr int answer = 42;
int *p = &answer;
*p = 8675309;
cout << answer << '\n';
c.cc: In function 'int main()':
c.cc:2:10: error: invalid conversion from 'const int*' to 'int*'
constexpr int answer = 42;
int *p = const_cast<int *>(&answer);
*p = 8675309;
cout << *p << ' ' << answer << '\n';
8675309 42

Modified: 2018-01-07T22:53

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building