理解C++中花括号{}的作用

  • 前言

    {} 在C++中功能较多,笼统来讲,功能起源是“变量初始化”,其用于汇总函数statements,也可以抽象理解为对函数这个变量的初始化。

  • 功能案例

    • Functions
      void myfunction(datatype argument) {
        // any statement(s)
      }
      
    • Loops
      while (boolean expression) {
        // any statement(s)
      }
      
      do {
        // any statement(s)
      } while (boolean expression);
      
      for (initialisation; termination condition; incrementing expr) {
        // any statement(s)
      }
      
    • Conditional Statements
      if (boolean expression) {
        // any statement(s)
      }
      
      else if (boolean expression) {
        // any statement(s)
      }
      else {
        // any statement(s)
      }
      
    • Return {}

      return {} indicates “return an object of the function’s return type initialized with an empty”

    • Initialization

      The initialization of variables was uniformed in C++11. The rule is quite simple. {}-Initialization is always applicable.

  • References

  1. Reference > En > Language > Structure > Further syntax > Curlybraces
  2. What does “return {}” statement mean in C++11?
  3. Modernes C++ : {} - Initialization
  4. Use of Curly Brackets (Braces) Around a variable C++

猜你喜欢

转载自blog.csdn.net/The_Time_Runner/article/details/107290411