silly safe coding with c++

Being anti-C++ is all the rage these days, with the programming hoi polloi singing hosannas to Rust ( https://www.rust-lang.org ) in particular. While I’ve worked a bit with Rust (and Google Go), I’m coming back around again to C++, specifically C++11 (the standard passed in 2011) or later, such as C++14 and C++17. For this coding experiment I’m using GCC/G++ 11.2 (a part of Mint Linux 21) and Boost 1.80 ( https://www.boost.org ). I also created this to try out using big numbers, which you can do natively within Python and Julia. Anyway, here’s the code.

#include <boost/multiprecision/cpp_int.hpp>#include <algorithm>#include <iostream>#include <iomanip>using boost::multiprecision::cpp_int;void factorial(cpp_int n) {cpp_int a = 1;std::cout << std::right << std::setw(4) << std::fixed << n;while ( n > 0 ) {a = a * n;n--;}std::cout << std::left << "! = " << a << std::endl;}int main(int argc, char *argv[]) {// Uncomment the following line to debug cli input.// std::copy(argv, argv + argc, std::ostream_iterator<char *>(std::cout, "\n"));for (int i = 1; i < argc; factorial(std::stoi(argv[i++])));return 0;}

And here’s a run.

I patterned this after another post where I wrote the equivalent simple factorial program in Julia and Python ( /2022/01/15/silly-coding/ ). What made the Python and Julia programs work is that both will work with arbitrarily sized integers. I had thought I might write something equivalent in C++, but then it quickly dawned on me that this arbitrarily sized integers are a common need, which is why they’re in Python and Julia. Sure enough, I quickly found support in Boost, using the Multiprecision data type cpp_int. What’s more the math and comparison operators are all overloaded so that the code looks no different using the big integer type as for a regular integer data type.

I call this safe because I’ve used as much pre-coded software as possible, knowing that all of it has been properly designed, coded, and tested. Yes, I could write it all myself, but it wouldn’t be as safe or trustworthy as it is now. Yes, it’s still fragile. For example I can pass bad values on the command line that don’t convert to an int and it will core dump (I know, I tried it out). But for basic testing, and as an example, I’m quite pleased how little I did code in order to make this work.

I know that working with C and C++ aren’t cool right now, but I’ll say what I’ve always said in the past. Learn the language, no matter what it is, and learn the best idiomatic way to program in that language.