Note that there are some explanatory texts on larger screens.

plurals
  1. POCan someone explain what the ternary operator is doing in this code?
    text
    copied!<p>I found this example C code from <a href="http://mitpress.mit.edu/books/audio-programming-book" rel="nofollow">"The Audio Programming Book"</a>.</p> <p>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.</p> <p>I am OK with everything except the line with reads:</p> <pre><code>a = amps ? amps[i] : 1.f; </code></pre> <p>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.</p> <p>But the code compiles, so I am completely baffled by what is it NOT wrong, and just what it is doing exactly.</p> <p>If someone can explain what this is doing [is a traditional If/Else form] I would greatly appreciate it. </p> <pre><code>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 &lt; harms; i++) for(int n=0; n &lt; 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; } </code></pre> <p>Thanks</p> <p>Stan</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload