If Statements And Braces.. Different Result With/Without

后端 未结 3 771
小鲜肉
小鲜肉 2021-01-26 06:40

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..

F

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 06:47

    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.

提交回复
热议问题