If Statements And Braces.. Different Result With/Without

后端 未结 3 768
小鲜肉
小鲜肉 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 07:07

    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.

提交回复
热议问题