Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use constexpr logic?

Tags:

c++

constexpr

I would like to implement some constexpr logic in some piece of code. I am able to compile and execute this code without problem.

#include <iostream>

int main(){
    std::cout << "Starting c++ main" << std::endl;

    constexpr int val_1 = 100;
    int val_2;

    if constexpr (val_1 == 100){
        val_2 = 10;
    }
    else if constexpr (val_1 == 200){
        val_2 = 20;
    }

    std::cout << val_2 << std::endl;
}

But really, the val_2 should be a constexpr too. How can I get val_2 to be a constexpr? I tried several things, but with no success. If I declare val_2 as constexpr, then I am not allowed to change its value in the if statement. If I do not declare the constexpr variable before the body of the if statements, then it is (as expected) not defined outside of the if statement.

like image 891
Zorglub29 Avatar asked Sep 20 '26 22:09

Zorglub29


2 Answers

You can put the initializer in a ternary expression:

constexpr int val_2 = val_1 == 100 ? 10 : val_1 == 200 ? 20 : 0;

If your initialization logic is more complex you can write a constexpr function like this:

constexpr auto f(int val_1) 
{
  int val_2{};

  if (val_1 == 100){
    val_2 = 10;
  }

  else if (val_1 == 200){
    val_2 = 20;
  }

  return val_2;
}

and then:

constexpr int val_2 = f(val_1);

Also, note that if constexpr should only be used to conditionally compile code. You don't need it for regular control flow.

like image 93
cigien Avatar answered Sep 23 '26 11:09

cigien


You can use an immediately called lambda:

constexpr int val_2 = []() {
    if constexpr (val_1 == 100){
        return 10;
    }
    else if constexpr (val_1 == 200){
        return 20;
    }
}();

like image 21
Artyer Avatar answered Sep 23 '26 11:09

Artyer