Search Unity

pet peeve: unassigned local variables

Discussion in 'Burst' started by TheOtherMonarch, Apr 17, 2021.

  1. TheOtherMonarch

    TheOtherMonarch

    Joined:
    Jul 28, 2012
    Posts:
    866
    In C# you are required to assign a default value even when you know that it is safe not to do so. For example I know that weaponEntity and weaponIndex will be assigned by the following loop but you still get the C# error "unassigned local variable" if you try to use them without first assigning default values.

    I know that weapons.Length will be greater then 0 and I also know that for one weapon isCurrentWeapon will be true.

    Code (CSharp):
    1.        
    2.             for (int i = 0; i < weapons.Length; i++) //see if we should switch weapon
    3.             {
    4.                 if (weapons[i].isCurrentWeapon)
    5.                 {
    6.                     weaponIndex = i;
    7.                     weaponEntity = weapons[i];
    8.                 }
    9.             }
    10.  
    Any plans to change this behavior with Bursted code? Maybe wrapping in unsafe{}
     
  2. Actually, you will get
    CS0103: The name 'weaponIndex' does not exist in the current context
    since in C# you need to declare your variables (lately you get implicit default values, although in your case the default 0 for the weaponIndex is also not the best choice since it would select the first weapon in case of any logical error/mistake). I doubt that Burst could change the rules of the language this much since it is a compiler feature, burst is working on the IL which is after compiling, even if they wanted to. But I hope they don't want to, changing the rules of a language this way for a subset of an application is very dangerous.
     
  3. TheOtherMonarch

    TheOtherMonarch

    Joined:
    Jul 28, 2012
    Posts:
    866
    I meant something like this but you get the idea. C#'s default behavior is super annoying for low level and performant code.

    Code (CSharp):
    1.      
    2.   int weaponIndex;
    3.  
    4.   for (int i = 0; i < weapons.Length; i++) //see if we should switch weapon
    5.   {
    6.                 if (weapons[i].isCurrentWeapon)
    7.                 {
    8.                     weaponIndex = i;
    9.                 }
    10.    }
    11.  
     
    Last edited: Apr 18, 2021
  4. sheredom

    sheredom

    Unity Technologies

    Joined:
    Jul 15, 2019
    Posts:
    300
    As @Lurking-Ninja said - this isn't something we can fix in Burst because it is a C# language level warning.

    If you really really want uninitialized variables you could use a stackalloc + [SkipLocalsInit] (which we added in Burst 1.5), but you'd have to ensure any other stackalloc's you did use were set to zero explicitly.