walruz
walruz

Reputation: 1329

Forbid C preprocessor to change variable's name

Here is a code example

#define S 113

double some_func1()
{
    return S;
}

double some_funcN( float S )
{
    return S/0.1;
}

When I am trying to compile it I am getting this error:

error C2143: syntax error : missing ')' before 'constant'

I am wondering if it is possible to fix it without renaming the 'S' variable?

Upvotes: 1

Views: 240

Answers (1)

dbush
dbush

Reputation: 223872

The token S will be replaced with 113 everyplace it appears. You have a few options to fix this:

  • Rename the parameter to some_funcN:

    double some_funcN( float n )
    {
       return n/0.1;
    }
    
  • Undefine the constant before the function and redefine it after. This has the disadvantage that S is defined in multiple places, so I wouldn't recommend it:

    #undef S
    double some_funcN( float S )
    {
       return S/0.1;
    }
    #define S 113
    
  • Change S from a macro to a variable. This allows variable scoping rules to take effect so that the function parameter S masks the definition of the variable S declared at file scope.

    const int S = 113;
    

Upvotes: 2

Related Questions