C++4: Constant Variables and Expressions

nubb
4 min readJul 10, 2024

--

Good afternoon, Medium! Given how fast I’m going with my C++ learning journey, I’ve decided to start publishing a little bit more to accommodate my learning speed, so I can get more info out to you guys and more info into my head.

Anyway, we’ll be looking at constants in C++ today! From what I’ve learned, they’re very powerful and enable much cleaner and faster programs with the right technique, which is what I’ll be teaching you guys today!

Let’s get to it!

(I’ll soon be looking into strings and std::string! Source)

Constexpr int x { 4 + 1 };

Let’s go over how the const type qualifier works.

Const sets a variable to be a constant in the program, similar to how literals work to a certain degree. Constant variables cannot be changed after they’ve been initialized. Failing to assign a value to a constant after defining it results in a compilation error.

const int y {}; // legal since value-initializing sets the int to 0
const int z { 4+1 }; // constant expression, can use constexpr instead of const
const int a; // illegal, compilation error since const must be initialized

Above are some examples of valid and invalid uses of const. Constants can be used for programs like physics calculations where you might want to store something like the acceleration of gravity.

Before we continue to constant expressions and the constexpr keyword, I want to delve a bit deeper with literals, particularly string literals.

First things first, string literals are a collection of characters, usually placed between double quotes to be differentiated between char literals. “Hello, World!” is a string literal whereas ‘c’ is a char literal. Strings in C++ aren’t a fundamental data type, they are instead inherited from C and are called C-style strings or C strings.

Consider the following string:

"waffle" // wow, a string

// 'w' + 'a' + 'f' + 'f' + 'l' + 'e' + '\0'

This may appear to have just 6characters, but it has 7. The 7th character in the string is called a null terminator, and is used to mark the end of the string.

That’s all there is to gloss over with strings. Our last two topics to go over are the constexpr keyword and compile-time optimization.

Constexpr can be used to denote a constant expression, which is a fancy way of saying an expression containing compile-time constants and operators.

Consider the following example:

#include <iostream>

int main()
{

int x { 5-3 }; // constant expression containing literals + operator-

std::cout << "5 - 3 is " << x; // wow basic arithmetic
return 0;

}

Contrary to how stupid compilers can be sometimes, most modern C++ compilers will notice we’re doing basic arithmetic that it can evaluate before runtime of the program. This is called compile-time optimization, and it enables our compiler to evaluate expressions before finalizing our program executable, which results in simpler code that uses less memory.

Note that your compiler will avoid changes affecting the observable behaviour of your code. That is, it won’t affect the output of your code, only optimize the implemented logic.

It’s important to understand how const and constexpr should be used to get the most out of compile-time optimization. Consider the following declarations:

int a { 4 }; // not const, can't be used for const expressions
const int b { a + 3 }; // runtime constant since 'int a' isn't a const variable

// const variable but can't be used for const expressions
// only integral (int) const variables can be used for compile-time optimization
const double c { 3.0 };

const int d { 5 + 6 }; // compile-time constant, will be evaluated
const int e { d + 4 }; // compile-time constant using const variables, will be evaluated

// constexpr works with non-integral (e.g. double) types!
// this is a compile-time constant
// so we can use it in other const/constexpr variables
constexpr double f { 4.5 };
constexpr double g { f + 1.0 }; // this is legal and compiles!

// compilation error, must have a valid constant expression!
constexpr int h { a + 3 };

Ultimately, the takeaways we can derive from the above example are:

  1. Use constexpr when a constant expression is used for initialization of a const variable.
  2. If constexpr doesn’t work for our use case, use const instead.

DidEnjoyPost ? subscribe() : follow();

Yes, as I was writing up the draft for this post, I learned about the conditional operator which can be used to effectively create condensed if-else statements. I won’t be going over it since it’s a pretty small topic and would add a bit more clutter to the next post than actionable information.

Speaking of “the next post”, I’m unsure what I’ll be learning within the next few days on my learning journey, so I suppose we’ll all be in for a surprise sometime next week in regard to what new stuff we’ll learn about.

Anyway, thanks a bunch for reading this blog post! I’m pleased with all the claps and support recently, it means a lot to me :)

I’ll see you guys next week. Have a good rest of your day, Medium.

If you enjoyed this blog post, consider following me or subscribing to support me!

Check out my GitHub and Portfolio!

--

--

nubb

Some guy programming and telling the world about it || Check out my projects here: https://github.com/nubbsterr