How to make calulation at compile time in C++

1 Answer

0 votes
#include <iostream>

constexpr int sum_of_1_to_n(const int n) {
	return n * (n + 1) / 2;
}

int main() {
    const int n = 5;
    
    auto sum = sum_of_1_to_n(n);

    std::cout << sum;
}
 
 
 
 
/*
run:
 
15
 
*/

 



answered Dec 8, 2023 by avibootz

Related questions

1 answer 134 views
2 answers 161 views
1 answer 152 views
1 answer 136 views
...