📜  我们如何使用逗号运算符代替花括号?

📅  最后修改于: 2021-05-30 10:10:57             🧑  作者: Mango

在C和C++中,可以在两种情况下使用逗号(,):

  1. 逗号作为运算符
  2. 以逗号作为分隔符

但是在本文中,我们将讨论如何将逗号用作花括号

花括号用于定义函数主体和控制语句的范围。大括号({)表示范围的开始,大括号(})表示范围的结束。也可以在控制语句中使用逗号运算符来定义范围,而不是使用花括号。

在if-else语句中用逗号运算符代替花括号:

例子:

// C++ program to show how to use
// comma in place of curly braces
// for if-else statements
  
#include 
using namespace std;
  
void func(int num)
{
    if (num < 10)
        cout << "It shows how we can use "
             << "comma operator in place of curly braces.\n",
            cout << "Entered number is less than 10\n",
            cout << "end of if block is encountered\n\n";
    else
        cout << "Now we are in else part\n",
            cout << "Entered number is greater than 10\n",
            cout << "End of else is encountered\n\n";
}
  
int main()
{
    int num = 5;
    func(num);
  
    num = 20;
    func(num);
  
    return 0;
}
输出:
It shows how we can use comma operator in place of curly braces.
Entered number is less than 10
end of if block is encountered

Now we are in else part
Entered number is greater than 10
End of else is encountered

逗号运算符代替循环中的花括号:

例子:

// C++ program to show how to use
// comma in place of curly braces
// for loops
  
#include 
using namespace std;
  
void func(int num)
{
    for (int i = 0; i < num; i++)
        cout << "It shows how we can use ",
            cout << "comma operator in place of curly braces.\n",
            cout << "Loop traversal number: ",
            cout << i << "\n\n ";
}
  
int main()
{
    int num = 5;
    func(num);
  
    return 0;
}
输出:
It shows how we can use comma operator in place of curly braces.
Loop traversal number: 0

 It shows how we can use comma operator in place of curly braces.
Loop traversal number: 1

 It shows how we can use comma operator in place of curly braces.
Loop traversal number: 2

 It shows how we can use comma operator in place of curly braces.
Loop traversal number: 3

 It shows how we can use comma operator in place of curly braces.
Loop traversal number: 4

注意:该块的最后一条语句必须以分号终止。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”