{"id":5032,"date":"2016-11-15T20:00:29","date_gmt":"2016-11-15T20:00:29","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/constexpr-functions\/"},"modified":"2023-06-26T12:36:09","modified_gmt":"2023-06-26T12:36:09","slug":"constexpr-functions","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/constexpr-functions\/","title":{"rendered":"constexpr Functions"},"content":{"rendered":"<p><span style=\"font-family: courier new,courier;\">constexpr<\/span> functions are functions that can be executed at compile time. Sounds not so thrilling. But it is. Trust me. You can perform with <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions a lot of calculations at compile time. Therefore, the calculation result is at&nbsp;runtime as a constant in ROM available. In addition, <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions are implicitly <span style=\"font-family: courier new,courier;\">inline.<\/span><\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<p>The syntax of <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions was significantly improved with the change from C++11 to C++14. The positive list from C++11 is with C++14 negative. In C++11, you had to remember which feature you can use in a <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions. With C++14, you only have to remember which feature you can&#8217;t use in a <span style=\"font-family: courier new,courier;\">constexpr<\/span> function.&nbsp;<\/p>\n<h2>C++11<\/h2>\n<p>For constexpr functions, there are a&nbsp;few restrictions<strong>:<\/strong><\/p>\n<p>The <strong>function<\/strong><\/p>\n<ul>\n<li>has to be non-virtual.<\/li>\n<li>has to have arguments and a return value of a <a href=\"http:\/\/en.cppreference.com\/w\/cpp\/concept\/LiteralType\">literal type<\/a>. Literal types are the types of <a href=\"https:\/\/www.modernescpp.com\/index.php\/constexpr-variables-and-objects\">constexpr variables<\/a>.<\/li>\n<\/ul>\n<p>The restriction goes on with the<strong> function body.<\/strong> The key points are that<\/p>\n<ul>\n<li>it has to be defined with the keyword <span style=\"font-family: courier new,courier;\">default<\/span> or <span style=\"font-family: courier new,courier;\">delete<\/span> or<span style=\"font-family: courier new,courier;\"><\/span><span style=\"font-family: courier new,courier;\"><\/span><\/li>\n<li>can only have one return statement.<\/li>\n<\/ul>\n<p>Is it possible to define a meaningful function with such restrictions? Because <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions can not have a conditional like <span style=\"font-family: courier new,courier;\">if<\/span> or a loop. Yes. Look at the constexpr functions in the&nbsp;post<a href=\"https:\/\/www.modernescpp.com\/index.php\/constant-expressions-with-constexpr\"> Constant expressions with constexpr<\/a>. Only the function getAverageDistance requires the C++14 standard.&nbsp;<\/p>\n<p>Fortunately, we have the ternary operator and recursion in C++. Therefore, I can implement the gcd algorithm as <span style=\"font-family: courier new,courier;\">a constexpr<\/span> function.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ constexpr11.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n\r\nconstexpr <span style=\"color: #2b91af;\">int<\/span> gcd(<span style=\"color: #2b91af;\">int<\/span> a, <span style=\"color: #2b91af;\">int<\/span> b){\r\n  <span style=\"color: #0000ff;\">return<\/span> (b== 0) ? a : gcd(b, a % b);\r\n}\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n  \r\n  std::cout &lt;&lt; std::endl;\r\n  \r\n  constexpr <span style=\"color: #2b91af;\">int<\/span> i= gcd(11, 121);\r\n  \r\n  <span style=\"color: #2b91af;\">int<\/span> a= 11;\r\n  <span style=\"color: #2b91af;\">int<\/span> b= 121;\r\n  <span style=\"color: #2b91af;\">int<\/span> j= gcd(a,b);\r\n\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"gcd(11,121): \"<\/span> &lt;&lt; i &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"gcd(a,b): \"<\/span> &lt;&lt; j &lt;&lt; std::endl;\r\n  \r\n  std::cout &lt;&lt; std::endl;\r\n \r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>I implemented in line 6 the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Euclidean_algorithm\">Euclidean algorithm<\/a> with the help of the ternary operator and recursion. Comprehensible code looks different. Of course, I can invoke the gcd function with arguments that are non-constant expressions (lines 15 and 16). Therefore, the result will be calculated at runtime and can only be taken by a non-constant expression (line 17).&nbsp;<\/p>\n<p>The result is a little bit boring. But wait for a second.<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5028\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/constexpr11.png\" alt=\"constexpr11\" width=\"668\" height=\"201\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/constexpr11.png 668w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/constexpr11-300x90.png 300w\" sizes=\"auto, (max-width: 668px) 100vw, 668px\" \/><\/p>\n<p>A glimpse of the assembler&#8217;s instructions is quite enlightening.&nbsp;<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5029\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/constexpr11Objectdump.png\" alt=\"constexpr11Objectdump\" width=\"800\" height=\"293\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/constexpr11Objectdump.png 1014w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/constexpr11Objectdump-300x110.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/constexpr11Objectdump-768x282.png 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><\/p>\n<p>The call of the <span style=\"font-family: courier new,courier;\">constexpr<\/span> function in line 13 causes the result of gcd(11, 121) to be available in the object file. This is opposite to the function call in line 17. At first, the processor has to push the variables on the stack (Instructions 400939 &#8211; 400941 in the object dump). Second, the processor has to invoke (<span style=\"font-family: courier new,courier;\">callq<\/span>) the function and store the result in the variable j (400948). What a difference!<\/p>\n<p>Of course, you can define more powerful <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions by calling ternary operators from ternary operators. This technique is <a href=\"https:\/\/en.wikipedia.org\/wiki\/Turing_completeness\">Turing complete<\/a>. So you can compute all that is computable. Fortunately, you don&#8217;t have to do that. You can use the C++14 <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions, which behave almost like ordinary functions.&nbsp;&nbsp;<\/p>\n<\/p>\n<h2>C++14<\/h2>\n<p><span style=\"font-family: courier new,courier;\">constexpr<\/span> <span>can have<\/span><\/p>\n<ul>\n<li>conditional jump instructions or loop instructions.<\/li>\n<li>more than one instruction.<\/li>\n<li><span style=\"font-family: courier new,courier;\">constexpr<\/span> functions.<\/li>\n<li>fundamental data types that have to be initialized with a constant expression.<\/li>\n<\/ul>\n<p>The difference between ordinary functions to <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions in C++14 is minimal. <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions can not have <span style=\"font-family: courier new,courier;\">static<\/span> or <span style=\"font-family: courier new,courier;\">thread_local<\/span> data. Either can they have a<span style=\"font-family: courier new,courier;\"> try<\/span> block or a <span style=\"font-family: courier new,courier;\">goto<\/span> instruction? Therefore, it&#8217;s quite easy to implement the gcd algorithm in C++14 as a <span style=\"font-family: courier new,courier;\">constexpr<\/span> function.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24\r\n25\r\n26\r\n27\r\n28\r\n29<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ constexpr14.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n\r\nconstexpr <span style=\"color: #0000ff;\">auto<\/span> gcd(<span style=\"color: #2b91af;\">int<\/span> a, <span style=\"color: #2b91af;\">int<\/span> b){\r\n  <span style=\"color: #0000ff;\">while<\/span> (b != 0){\r\n    <span style=\"color: #0000ff;\">auto<\/span> t= b;\r\n    b= a % b;\r\n    a= t;\r\n  }\r\n  <span style=\"color: #0000ff;\">return<\/span> a;\r\n}\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n  \r\n std::cout &lt;&lt; std::endl;\r\n  \r\n  constexpr <span style=\"color: #2b91af;\">int<\/span> i= gcd(11,121);\r\n  \r\n  <span style=\"color: #2b91af;\">int<\/span> a= 11;\r\n  <span style=\"color: #2b91af;\">int<\/span> b= 121;\r\n  <span style=\"color: #2b91af;\">int<\/span> j= gcd(a,b);\r\n\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"gcd(11,121): \"<\/span> &lt;&lt; i &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"gcd(a,b): \"<\/span> &lt;&lt; j &lt;&lt; std::endl;\r\n  \r\n  std::cout &lt;&lt; std::endl;\r\n \r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>I skip the output of the program because it&#8217;s identical to the output of the C++11 variant.<\/p>\n<p>Thanks to a discussion with Odin Holmes in the Facebook group of this blog <a href=\"https:\/\/www.facebook.com\/groups\/modernescpp\/\">Modernes C++&nbsp;<\/a>I want to present a very interesting use case for <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions.<span style=\"font-family: courier new,courier;\"><\/span><\/p>\n<h2>Pure functions<\/h2>\n<p>You can execute constexpr functions at runtime. If you take the return value of a <span style=\"font-family: courier new,courier;\">constexpr<\/span> function by a constant expression, the compiler will perform the function at compile time. The question is: Is there a reason to perform a constexpr function at runtime? Of course, you have the <span style=\"font-family: courier new,courier;\">constexpr<\/span> function, so you can use it at runtime. But there is a much more convincing reason.<\/p>\n<p>A constexpr function can be potentially performed at compile time. There is no state at compile time. At compile time, we are in a pure functional sublanguage of the imperative programming language C++. In particular, that means that at compile time, executed functions have to be pure functions. When you use this <span style=\"font-family: courier new,courier;\">constexpr<\/span> function at runtime, the function keeps pure. Pure functions always return the same result when given the same arguments. Pure functions are like infinitely large tables from which you get your value. Referential transparency is the guarantee that an expression always returns the same result when given the same arguments.<\/p>\n<p>Pure functions have a lot of advantages:<\/p>\n<ul>\n<li>The result can replace the function call.<\/li>\n<li>The execution of pure functions can automatically be distributed to other threads.<\/li>\n<li>The function call can be reordered.<\/li>\n<li>They can easily be refactored.<\/li>\n<\/ul>\n<p>The last three points hold because pure functions have no state and have, therefore, no dependency on the environment. Pure functions are often called mathematical functions.<\/p>\n<p>There are a lot of good reasons to use constexpr functions. The table shows the critical points of pure and impure functions.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5030\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/PureVersusImpure.png\" alt=\"PureVersusImpure\" width=\"700\" height=\"170\" style=\"margin: 15px;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/PureVersusImpure.png 853w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/PureVersusImpure-300x73.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/PureVersusImpure-768x186.png 768w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/p>\n<p>I will write in a few weeks about functional programming in C++. Then I will explain the details of pure functions and pure functional programming.<\/p>\n<h3>Pure and purer<\/h3>\n<p>I want to stress one point. constexpr functions are not per se pure. Thanks to Marcel Wid, who made me aware of this. <span style=\"font-family: courier new,courier;\">constexpr<\/span> functions are a lot purer than ordinary functions. E.g., you can only invoke a <span style=\"font-family: courier new,courier;\">constexpr<\/span> function in a <span style=\"font-family: courier new,courier;\">constexpr<\/span> function. Those who want only to use pure functions should study <a href=\"https:\/\/www.haskell.org\/\">Haskell.<\/a> The exceptionally well-written introduction to Haskell&nbsp;<a href=\"https:\/\/www.haskell.org\/\"> <\/a><a href=\"http:\/\/learnyouahaskell.com\/\">Learn You a Haskell For Great Good<\/a> from Miran Lipovaca is available online.<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>In the post <a href=\"https:\/\/www.modernescpp.com\/index.php\/more-and-more-save\">More and more save<\/a>, I successively optimized the gcd algorithm. Thanks to the type-traits library and <span style=\"font-family: courier new,courier;\">static_assert<\/span>, this was quite impressive. But that was not the whole story about the type traits. By analyzing the type system of your code, you can write self-optimizing programs. How? Read the<a href=\"https:\/\/www.modernescpp.com\/index.php\/type-traits-performance-matters\"> next post.<\/a><span id=\"transmark\"><\/span><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>{tooltip} <img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5031\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/title_page_small.png\" alt=\"title page small\" width=\"166\" height=\"212\" \/>{end-texte}<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5031\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/11\/title_page_small.png\" alt=\"title page small\" style=\"margin: 3px;\" width=\"167\" height=\"213\" \/> Go to <a href=\"https:\/\/leanpub.com\/cpplibrary\"> <\/a><a href=\"https:\/\/leanpub.com\/cpplibrary\">Leanpub\/cpplibrary<\/a> <a href=\"https:\/\/leanpub.com\/cpplibrary\"> <\/a><strong>&#8220;What every professional C++ programmer should know about the C++ standard library&#8221;.<\/strong> <a href=\"https:\/\/leanpub.com\/cpplibrary\"><\/a>{end-tooltip} &nbsp; <strong><span class=\"h3\">Get your e-book. Support my blog.<\/span><\/strong><\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>constexpr functions are functions that can be executed at compile time. Sounds not so thrilling. But it is. Trust me. You can perform with constexpr functions a lot of calculations at compile time. Therefore, the calculation result is at&nbsp;runtime as a constant in ROM available. In addition, constexpr functions are implicitly inline.<\/p>\n","protected":false},"author":21,"featured_media":5028,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[364],"tags":[428],"class_list":["post-5032","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-embedded","tag-constexpr"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5032","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=5032"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5032\/revisions"}],"predecessor-version":[{"id":6925,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5032\/revisions\/6925"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5028"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5032"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5032"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5032"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}