If Statements And Braces.. Different Result With/Without

只谈情不闲聊 提交于 2019-12-02 07:38:24

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.

In the first case, you are not executing a return statement if the condition isn't met. Presumably the function is returning garbage.

In the second case, because there are no braces, only one line is dependent on the condition. The return statement is executed regardless. In other words, your second example is equivalent to:

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;
};

You have an if statement. If the statement evaluates to true, it will execute the operation immediately following it. In order to do more than one operation at once, you must enclose them in curly braces.

You're getting a strange answer with braces because if J is uppercase, your if statement is false, you skip past the braces, and you don't have a specified return value (hence the nonsense return value). You need to say what to return if your if statement isn't true.

Your second piece of code works because only the first line after the if statement is controlled by the if. This is essentially you being lucky here with - if you had two operations you had wanted to do, you'd still be getting garbage. It's generally therefore good practice to explicitly specify what code you want executed by your if statement by putting it in curly braces, even if it's one operation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!