Skip to content

C++ Best practices for dealing with many constants, variables in scientific codes

An answer to this question on the Scientific Computing Stack Exchange.

Question

I am developing a code to simulate fluid flow with biological substances present in the flow. This involves the standard Navier-Stokes equations coupled to some additional biological models. There are many parameters/constants.

I have written functions to handle the major computations, but a problem I am having is the large number of constants/parameters that these computations depend on. It seems cumbersome to pass 10-20 arguments to a function.

One alternative is to make all the constants global variables, but I know this is frowned upon in C++.

What is the standard way of handling many inputs to a function? Should I make a struct and pass that instead?

Thank you

Answer

If you have constants that will not change before runs, declare them in a header file:

//constants.hpp
#pragma once 
namespace constants {
  constexpr double G        = 6.67408e-11;
  constexpr double M_EARTH  = 5.972e24;
  constexpr double GM_EARTH = G*M_EARTH; 
}
#endif
//main.cpp
using namespace constants;
auto f_earth = GM_EARTH*m/r/r;  //Good
auto f_earth = G*M_EARTH*m/r/r; //Also good: compiler probably does math here too

The reason why you would want to do this is that it allows the compiler to calculate constant values before run-time, which is good if you have a lot of them.

You can also use a simple class to pass values around:

class Params {
 public:
  double a,b,c,d;
  Params(std::string config_file_name){
    //Load configuration here
  }
};
void Foo(const Params &params) {
  ...
}
int main(int argc, char **argv){
  Params params(argv[1]);
  Foo(params);
}