Constant Expressions with constexpr

Contents[Show]

You can define with the keyword constexpr an expression that can be evaluated at compile time. constexpr can be used for variables, functions, and user-defined types. An expression that is evaluated at compile time has a lot of advantages. For example, constexpr variables and instances of user-defined types are automatically thread-safe and can be stored in ROM; constexpr functions evaluated at compile-time are done with their work at run time.

All done at compile time

I already have indicated it in my post on User-defined literals.  The calculation of how many kilometers per week I drive on average has a massive optimization potential. In this post, I will solve my promise. To make it easy for you. Here is the program from the post User-defined literals once more.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// userdefinedLiterals.cpp

#include <iostream>

namespace Distance{

  class MyDistance{
    public:
      MyDistance(double i):m(i){}

      friend MyDistance operator+(const MyDistance& a, const MyDistance& b){
        return MyDistance(a.m + b.m);
      }
      friend MyDistance operator-(const MyDistance& a,const MyDistance& b){
        return MyDistance(a.m - b.m);
      }
	  
      friend MyDistance operator*(double m, const MyDistance& a){
        return MyDistance(m*a.m);
}
friend MyDistance operator/(const MyDistance& a, int n){ return MyDistance(a.m/n); } friend std::ostream& operator<< (std::ostream &out, const MyDistance& myDist){ out << myDist.m << " m"; return out; } private: double m; }; namespace Unit{ MyDistance operator "" _km(long double d){ return MyDistance(1000*d); } MyDistance operator "" _m(long double m){ return MyDistance(m); } MyDistance operator "" _dm(long double d){ return MyDistance(d/10); } MyDistance operator "" _cm(long double c){ return MyDistance(c/100); } } } Distance::MyDistance getAverageDistance(std::initializer_list<Distance::MyDistance> inList){ auto sum= Distance::MyDistance{0.0}; for (auto i: inList) sum = sum + i ; return sum/inList.size(); } using namespace Distance::Unit; int main(){ std:: cout << std::endl; auto work= 63.0_km; auto workPerDay= 2 * work; auto abbrevationToWork= 5400.0_m; auto workout= 2 * 1600.0_m; auto shopping= 2 * 1200.0_m; auto distPerWeek1= 4*workPerDay-3*abbrevationToWork+ workout+ shopping; auto distPerWeek2= 4*workPerDay-3*abbrevationToWork+ 2*workout; auto distPerWeek3= 4*workout + 2*shopping; auto distPerWeek4= 5*workout + shopping; auto averageDistance= getAverageDistance({distPerWeek1,distPerWeek2,distPerWeek3,distPerWeek4}); std::cout << "averageDistance: " << averageDistance << std::endl; std::cout << std::endl; }

 

How can I massively improve the program? Relatively easy by using constexpr. My key idea is to declare all instances of MyDistance in the main program as constexpr. Therefore, I say to the compiler: Instantiate the objects at compile time. But the compiler can only perform its job if the instantiation is based on constant expressions. I will get a compiler error if the compiler can not do it.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs.

 

 

Subscribe via E-Mail.

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// userdefinedLiteralsConstexpr.cpp

#include <iostream>

namespace Distance{

  class MyDistance{
    public:
      constexpr MyDistance(double i):m(i){}

      friend constexpr MyDistance operator+(const MyDistance& a, const MyDistance& b){
        return MyDistance(a.m + b.m);
      }
      friend constexpr MyDistance operator-(const MyDistance& a,const MyDistance& b){
        return MyDistance(a.m - b.m);
      }
	  
      friend constexpr MyDistance operator*(double m, const MyDistance& a){
        return MyDistance(m*a.m);
      }
	  
      friend constexpr MyDistance operator/(const MyDistance& a, int n){
        return MyDistance(a.m/n);
      }
	  
      friend std::ostream& operator<< (std::ostream &out, const MyDistance& myDist){
        out << myDist.m << " m";
        return out;
      }
    private:
double m; }; namespace Unit{ constexpr MyDistance operator "" _km(long double d){ return MyDistance(1000*d); } constexpr MyDistance operator "" _m(long double m){ return MyDistance(m); } constexpr MyDistance operator "" _dm(long double d){ return MyDistance(d/10); } constexpr MyDistance operator "" _cm(long double c){ return MyDistance(c/100); } } } constexpr Distance::MyDistance getAverageDistance(std::initializer_list<Distance::MyDistance> inList){ auto sum= Distance::MyDistance{0.0}; for (auto i: inList) sum = sum + i ; return sum/inList.size(); } using namespace Distance::Unit; int main(){ std:: cout << std::endl; constexpr auto work= 63.0_km; constexpr auto workPerDay= 2 * work; constexpr auto abbrevationToWork= 5400.0_m; constexpr auto workout= 2 * 1600.0_m; constexpr auto shopping= 2 * 1200.0_m; constexpr auto distPerWeek1= 4*workPerDay-3*abbrevationToWork+ workout+ shopping; constexpr auto distPerWeek2= 4*workPerDay-3*abbrevationToWork+ 2*workout; constexpr auto distPerWeek3= 4*workout + 2*shopping; constexpr auto distPerWeek4= 5*workout + shopping; constexpr auto averageDistance= getAverageDistance({distPerWeek1,distPerWeek2,distPerWeek3,distPerWeek4}); std::cout << "averageDistance: " << averageDistance << std::endl; std::cout << std::endl; }

 

The result of the calculation is not so exciting. To compile the program, I have to use a C++14 compiler. A current GCC of clang is fine. The current Microsoft Visual 2015 C++-Compiler supports only C++11. Therefore, cl.exe will not compile the function getAverageDistance. In C++11, a constexpr function can only have a return statement.

userdefinedLiteralsConstexprResult

But it is very exciting to look at the assembler instructions. To simplify my job, I use the interactive compiler hosted on https://gcc.godbolt.org/. Have I already mentioned that I like this tool very much?

 userdefinedLiteralsConstexpr

 

How should we interpret the results? Quite easy. In the main program (lines 64 - 75) defined constant expressions are part of the assembler program. Or to say it differently. All calculations are done at compile time. At run time, the program consists only of the already calculated expressions. That is an extremely easy job for the run time.

What's next?

So, that's enough to make you keen on more. The details will follow in the next post. I will look deeper into constexpr variables, functions, and user-defined types. You have to keep a few rules in mind. Firstly, C++14 constexpr functions are more powerful than C++11 constexpr functions. Secondly, you can execute constexpr functions at run time. Lastly, there are a few restrictions for user-defined types to instantiate them at compile time.

 

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Dominik Vošček, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

 

 

 

 

 

Tags: constexpr

Comments   

0 #1 TanDo 2016-11-23 04:13
"Firstly, C++14 constexpr functions are more powerful than C++ constexpr functions"
I think you miss the word: powerful than C++ 11 constexpr
Quote
0 #2 Rainer Grimm 2016-11-23 07:29
Quoting TanDo:
"Firstly, C++14 constexpr functions are more powerful than C++ constexpr functions"
I think you miss the word: powerful than C++ 11 constexpr

Thanks, I will fix it.
Quote
0 #3 Muado 2018-06-07 08:27
i really like your blog. Very useful informations. Thx
Quote
0 #4 Muado 2018-06-15 11:49
awesome information thanks for sharing
Quote
0 #5 Anil Kumar Soni 2020-07-15 02:09
What is this function
MyDistance operator "" _km(long double d){
return MyDistance(1000*d);
}
Please explain
Quote

Mentoring

Stay Informed about my Mentoring

 

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 2638

Yesterday 4791

Week 2638

Month 192714

All 11673868

Currently are 393 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments