我们知道在c语言中,'while'关键字用于定义一个循环,该循环根据传递给循环的条件来工作。现在,由于条件可以有两个值,即真或假,所以如果条件为真,则while块内的代码将被重复执行,如果条件为假,则代码将不会被执行。
现在,通过将参数传递给while循环,我们可以区分while(1)和while(0),因为while(1)是一个条件始终被视为真的循环,因此块内的代码将开始重复执行。此外,我们可以说明,传递给循环并使条件为真的不是1,而是如果任何非零整数传递给while循环,则它将被视为真条件,因此代码开始执行。
另一方面,while(0)是一个条件始终被视为假的循环,因此块内的代码永远不会开始执行。此外,我们可以说明,只有0被传递给循环并使条件为假,因此如果任何其他非零整数(可以是负数)被传递给while循环,则它将被视为真条件,因此代码开始执行。
上面讨论的观点可以通过以下示例进行演示。
示例while(1)的示例
#include using namespace std;main(){ int i = 0; cout << "loop get started"; while(1){ cout << "the value of i: "; if(i == 10){ //when i is 10, then come out from loop break; } } cout << "loop get ended" ;}
输出loop get startedthe value of i: 1the value of i: 2the value of i: 3the value of i: 4the value of i: 5the value of i: 6the value of i: 7the value of i: 8the value of i: 9the value of i: 10loop gets ended
示例while(0) 示例
#includeusing namespace std;main(){ int i = 0; cout << "loop get started"; while(0){ cout << "the value of i: "; if(i == 10){ //when i is 10, then come out from loop break; } } cout << "loop get ended" ;}
输出loop get startedloop get ended
以上就是在c语言中,while(1)和while(0)之间的区别是什么?的详细内容。