Question

I have the following code:

#include <stdio.h>
#include <stdarg.h>

#define A 10
#define B 20
#define C 30

int m = A + B;
const int n = A + B + C;

void foo1(int x) {
    m += A + B + x;
}

void foo2(int x = B, int y = C, ...) {
    m += B + C + x;
    if (m > n) foo1(y);
    /* Some statements here */
}
/* And MUCH MORE functions and some global variables like these here. */

int main() {
    /* Some statements here */
    return 0;
}

I want these A, B, C as runtime dependant variables which will be processed in main() function (no #define). What is the best way to change the preprocessor variables into runtime dependant variables without changing most of the code? (Assume that the whole code is more than 1000 lines.)

Was it helpful?

Solution

Since no one answered to my question, I'm finally answering it based on my practical work. Though I'm not sure whether there is a better way of changing preprocessor variables into runtime dependant variables.

Cure for the situation:

  • Firstly, uncomment the necessary "#define" statements in the code. This will highlight the errors (through Visual Studio Intellisense, for example) in variables related to preprocessor variables.
  • Then move the highlighted variables' assignment in main function (or, other function(s)). You need not move the variables inside functions but outside all functions (that means global variables). Use Find-and-Replace, Regex, macro automation for the task, if possible.
  • Then declare preprocessor variable names globally. Constant variables will be gone but there's no choice, I think.
  • Finally, check for errors in the code and debug if necessary.

Prevention of the situation:

Prevention is better than cure. Well-planned project should be maintained. If there's a good possibility of runtime dependant variable, do not use preprocessor statement for it.

Finalized code of the question's code:

#include <stdio.h>
#include <stdarg.h>

/* Preprocessor variable names as global variables */
int A, B, C;

/* Assignments are moved */
int m;
int n;  /* no more constant */

void foo1(int x) {
    m += A + B + x;
}

void foo2(int x = B, int y = C, ...) {
    m += B + C + x;
    if (m > n) foo1(y);
    /* Some statements here */
}
/* And MUCH MORE functions and some global variables like these here. */

int main() {
    /*
    A, B, C actually runtime dependant.
    But for simplicity, they are hardcoded here.
    */
    A = 10;
    B = 20;
    C = 30;

    /* Assignment of global variables */
    m = A + B;
    n = A + B + C;

    /* Some statements here */
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top