Search code examples
c#reliability

How reliable is an if statement?


If I run the following code,

while(true)
{
    if(true)
    {
        Console.WriteLine("True");
    }
    else
    {
        Console.WriteLine("False")
    }
}

How reliable is it that the Console will print "True" ? Will if ever print "False" ? Why ?

Edit: I had no idea that physical components of a computer were so perfect.


Solution

  • The question is a bit more interesting than downvoting peple think.

    Sure, that conditional logic is really perfect. Visual studio generates a warning: Unreachable code detected, so the else branch will never ever be executed.

    Even in case of hardware fault, computer / operating system / program itself is more likely to crash than the second brunch to execute.

    But it does not mean that "False" will not be printed. String literals in dotnet normally are interned. Look at this hack:

    static unsafe void Main(string[] args)
    {
        // "True" is interned now
        string s = "True";
    
        // unsafe access to the interned string
        fixed (char* h = s)
        {
            // We have to change the length of the string.
            // The length is stored as integer value right before the first char
            ((int*)h)[-1] = 5;
    
            // Next operations change content of interned string
            h[0] = 'F';
            h[1] = 'a';
            h[2] = 'l';
            h[3] = 's';
    
            // But next one is dangerous - they can damage memory contents 
            h[4] = 'e';
        }
    
        // the most reliable code ever:)
        while (true)
        {
            if (true)
            {
                Console.WriteLine("True");
            }
            else
            {
                Console.WriteLine("False");
            }
        }
    }
    

    The else branch is not executed, which can be ensured with debugger, so the conditional logic is still consistent. However the program prints "False" even through the System.Console's method.

    This trick requres enabling the unsafe context in the compiler options, moreover, it can damage process's memory.