C++中的每个语句都必须按照基本的分号结束。然而,与其他语言不同,C++中的几乎所有语句都可以被当作表达式来处理。然而,在很少的情况下,我们可以编写一个没有分号的运行程序。 如果我们将语句放在带有一对空括号的If/switch/while/macro语句中,则不必以分号结尾。此外,调用返回void的函数在这里也不起作用,因为void函数不是表达式。我们可以使用逗号运算符,在运算符的右边有任何值。 例如:
null
- 使用 if语句 :
// CPP program to print
// Hello World without semicolon
// using if statement
#include <iostream>
int
main()
{
if
(std::cout <<
"Hello World "
)
{
}
}
输出:
Hello World
- 使用 switch语句 :
// CPP program to print
// Hello World without semicolon
// using switch statement
#include <stdio.h>
int
main()
{
switch
(
printf
(
"Hello World "
))
{
}
}
输出:
Hello World
- 使用 宏
// CPP program to print
// Hello World without semicolon
// using macros
#include <stdio.h>
#define GEEK printf("Hello World")
int
main()
{
if
(GEEK)
{
}
}
输出:
Hello World
- 使用 循环(while和for) : 在这里,重要的是要注意使用!(非运算符)在while循环中避免无限循环。
// CPP program to print
// Hello World without semicolon
// using if statement
#include<iostream>
int
main()
{
while
(!(std::cout <<
"Hello World"
))
{ }
// for loop can also be used
// where testing condition has cout statement
// for (;!(std::cout << "Hello World");)
// { }
}
Hello World
相关文章: 如何打印分号(;)在C/C++中不使用分号?
本文由 阿夫尼·纳格瓦尼 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END