Search code examples
c++if-statementbraces

If Statements And Braces.. Different Result With/Without


Alright, so I'm in the process of learning C++, and I've hit a strange effect while working with one of the tutorials, and I don't quite get while it's happening..

For the tutorial (copied from the example offered), I have written a function within a class template specialization that checks if the char is lowercase, and then makes it uppercase:

char uppercase ()
{
    //checks to see if "element"(char) is a lower-case letter between 'a' and 'z'
    if ((element >= 'a') && (element <= 'z'))
    {
        //changes value of "element" to be element + (value of A - Value of a)[-32]
        element += 'A' - 'a'; //element = element + -32
        return element;
    };
};

Now, strangely.. even if the char is already uppercase, this code still gets triggered. So if I call the function with a value of 'j', I obviously get 'J', as intended. However, if I call with a value of 'J', the function still goes through.. so instead of the function not changing anything, it instead returns '*'.

Now, interestingly.. if I remove the brackets from the if statement, it works as intended. So, with

char uppercase ()
{
    //checks to see if "element"(char) is a lower-case letter between 'a' and 'z'
    if ((element >= 'a') && (element <= 'z'))
        //changes value of "element" to be element + (value of A - Value of a)[-32]
        element += 'A' - 'a'; //element = element + -32
        return element;
};

it works completely as intended. Calling the function with the value 'J' just returns 'J', because the conditions weren't met, and thus no code was executed. Now, I know that braces are optional with if statements, but the tutorial says that braces are required for more than one statement.

It's also worth noting that adding an else to the statement using braces with just a plain return gives the desired effect, but this should be unnecessary, right?

So, basically.. am I missing something about braces, or is this just an issue with the compiler (Visual Studio 2012)?


Solution

  • That's per design, the if takes one statement only, the braces make a block one statement.

    If you want scope by indentation use Python.

    The problem with your code is that you do not return anything when the if statement does not match, which results in undefined behavior. Your compiler probably gives you a warning about that. Don't ignore compiler warnings.

    The second block of code is actually what you want, only change the variable element when your if matches, but always return the variable element.