Note that there are some explanatory texts on larger screens.

plurals
  1. POIn C#, can multiplications inside of an array declaration/initialization cause mayhem?
    text
    copied!<p>I am going a bit crazy here with the following section of code</p> <pre><code> public static readonly float f = 1.25f; public static void init(){ Debug.Log(f); // output: 1.25f FLIPPER_CENTERS = new float[,] { { (20*f), (27*f) }, { FLIPPER_WIDTH - (20*f), (27*f)}, { (6*f), (25*f) }, { MH_FLIPPER_WIDTH- (6*f), (25*f) }, { (8), (15)}, { (SMALL_FLIPPER_WIDTH - 8), (15)}, { (8), (20)}, { (67 - 8), (20)}, }; Debug.Log(FLIPPER_CENTERS[0,0]); // output: 0, expected 25; } </code></pre> <p>If I print the values of the first element of that array, I get <code>[0, 0]</code>. The last two elements are <code>[59, 20]</code>, as expected.</p> <p>The first value is supposed to be <code>[25, 33,75]</code>. Which I can get if I substitute <code>(20*f)</code> for <code>(20*1.25f)</code>.</p> <pre><code> { (20*1.25f), (27*1.25f) }, { FLIPPER_WIDTH - (20*f), (27*f)}, </code></pre> <p><strong>So here is the problem: if I leave the multiplication by f in the array initialization, the values are 0. However, if I change <code>f</code> to <code>1.25f</code> all is good.</strong></p> <p>I have tried to figure out what is going on, but to no avail. I am certain the value of <code>f</code> is <code>1.25f</code> and not <code>0</code>. Can anyone shed some light on this for me please?</p> <p>Edit:</p> <p>To prove that <code>f</code> is not <code>0</code>, I've tried <code>20/f</code> for the first element. That didn't throw an exception and the output was still <code>0</code>.</p> <p><strong>Partial Solution</strong></p> <p>Changing <code>f</code> from <code>readonly</code> to <code>const</code> solves the problem. However, I would really much like to know why this is happening.</p> <pre><code> public const float f = 1.25f; </code></pre> <p>All this is running in Unity, it may have something to do with it.</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