I'm writing a program in C in which there are several constants I would like all of my functions to use. So far, I have used macros. A simplified version of the program looks as follows.
#define CONSTANT 10 //int
int multiplication_by_constant(int a){ return a*CONSTANT;}
int main(){
for(int i = 1; i< 10; i++)
printf("%d\n",multiplication_by_constant(i));
}
Now I want to run experiments on the program by running it several times with different values of the constant. I want to automate this, and not re-compile each time I change CONSTANT. I used a simple solution by changing the macros to global variables, putting the original main function into a new 'program()' function, then to run the experiments in the main file, i.e.
int CONSTANT = 10; //int
int multiplication_by_constant(int a){ return a*CONSTANT;}
void program(){
for(int i = 1; i< 10; i++)
printf("%d\n",multiplication_by_constant(i));
}
int main(){
while(CONSTANT < 100){
program();
}
return 0;
}
I discovered that this implementation lead to quite a substantial loss of performance of the loop
for(int i = 1; i< 10; i++)
printf("%d\n",multiplication_by_constant(i));
which now requires around 50% more run time than when I was using the macro. Is this normal?
Can anyone suggest a more efficient way for me to run my experiment?
PS In C++, I would do this by defining a 'class program', setting CONSTANT to be a class member and 'multiplication_by_constant' a member function. I could then easily run the experiments through 'main' using the class definition, and I think I wouldn't have the efficiency loss... I have to use C in this implementation which is why I've resorted to the global variables and functions.