cast operators with defined constants

43 views Asked by At

I have checked that cast operators work fine also with #defined constants, e.g.

#define SAMPLES 100
#define SAMP_TIME_MAX 51

int main()
{
    float f_samp = (double) SAMPLES / SAMP_TIME_MAX;
    printf("f_samp = %f",f_samp);
    return 0;
}

My questions are:

  1. is it a good practice or is there any better way to obtain the same effect?
  2. how are the precedence rules, e.g. in the example above does (double) has effect on SAMPLES or on (SAMPLES / SAMP_TIME_MAX)?
1

There are 1 answers

0
kavulox On

When you define something, all that really happens at a high level is that the preprocessor goes around and replaces the instance of the definition with the value. So your example of:

#define SAMPLES 100
#define SAMP_TIME_MAX 51

int main()
{
    float f_samp = (double) SAMPLES / SAMP_TIME_MAX;
    printf("f_samp = %f",f_samp);
    return 0;
}

Is really just equivalent to:

int main()
{
    float f_samp = (double) 100 / 51;
    printf("f_samp = %f",f_samp);
    return 0;
}

So yes, its fine to cast it to a double. Also, you would want to cast to a float, or change f_samp to a double.