Question

I found this example C code from "The Audio Programming Book".

I understand basically what the code is doing. It takes an array of values that represent the amplitude of series of sine waves and adds them together to create a complex wave.

I am OK with everything except the line with reads:

a  = amps ?  amps[i] : 1.f; 

I know Ternary Operators are basically If/Else statement, but I cannot seem to figure out what this is doing exactly, because 'amps' is not defined earlier in the code. It doesn't make sense that amps is reusing amps[], it seem that would be a no no. I also haven't been able to find an example anywhere that matches up with this anywhere else.

But the code compiles, so I am completely baffled by what is it NOT wrong, and just what it is doing exactly.

If someone can explain what this is doing [is a traditional If/Else form] I would greatly appreciate it.

float* TableGEN::fourier_table(int harms, float *amps, int length, float phase)
{
   float a;
   float *table = new float[length+2];
   double w;
   phase *= (float)pi*2;  

   memset(table, 0, (length+2)*sizeof(float) );

   for(int i=0; i < harms; i++)
      for(int n=0; n < length+2; n++)
      {
           a  = amps ?  amps[i] : 1.f;     
           w = (i+1)*(n*2*pi/length);
           table[n] += (float) (a*cos(w+phase));
      }

   normalise_table(table, length , 1.0f );
   return table;
}

Thanks

Stan

Was it helpful?

Solution

It seems it's checking if amps is true and/or is set to something, and if it is, then grab the given index of it, else, return a float of 1.

So

if (amps)
{
   a = amps[i];
}
else
{
   a = 1.f;
}

Which is wonky/odd to be honest. It should really be checking if amps[i] is set, and then grab it. If not, then default to 1.f

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top