c++17学习笔记:在if和switch中申明变量

总的来说,这是一种新的语法糖,下面是一个在if中声明变量的例子

#include <iostream>

int main()
{
	// if 和 else 中都能访问到
    if (int x = 10; x < 5)
        std::cout << x << std::endl;
    else
        std::cout << "x >= 5, "
                  << "x is : " << x << std::endl;
}

switch同理

switch (int x = 2; x)
    {
    case 1:
        std::cout << "x is 1" << std::endl;
        break;
    case 2:
        std::cout << "x is 2" << std::endl;
    }
posted @ 2022-06-01 19:19  yuzuki_n  阅读(162)  评论(0)    收藏  举报