基本if else语句

Basic if else statements

本文关键字:语句 else if 基本      更新时间:2023-10-16

考虑一下我编写的使用和ifelse语句的代码

#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int a = 5;
if(a)
{
printf("if %dn" , ++a);
}
else
printf("else %dn" , a);
}

如果我设置int a = 5,它会打印输出"If 6">

但如果我设置int a = 0,它会打印值"else 0">

为什么会这样?原因是什么?

++aa的值增加一,并且是一个等于该增加值的表达式。

  1. a为5时,if (a)if (true),因为a为非零。因此运行printf("if %dn" , ++a);,该语句中的++a使a递增,并计算为递增的值6。

  2. a为0时,if (a)if (false)。因此printf("else %dn" , a);运行。CCD_ 18在这种情况下不改变。

我相信现在发生的是对if语句的理解混乱。

int main() {
int a =5;
if(a)
{
printf("if %dn" , ++a);
}
else
printf("else %dn" , a);
return 0;
}

此代码本质上等效于:

int main() {
int a =5;
printf("if %dn" , ++a);
return 0;
}

输出:6

如果a为0,则代码等效于:

int main() {
int a =0;
printf("else %dn" , a);  // Notice no ++
return 0;
}

输出:0

如果您要将代码写成:

int main() {
int a =5;
printf("if %dn" , a);  // Notice no ++
return 0;
}

输出:5

if将评估存储在括号中的值,例如:

int a = 0;
if(a)  // since a is 0, the value equates to false and the if is ignored
{
}
else // since the if evaluated to false it will do the else.
{

}

在以下情况下:

int a = 5;
if(a) // a is non-zero therefore it equates to true, and the if body is ran
{
}
else // since the if was true the else is ignored, and its body wont be run.
{

}

现在让我们来分析一下为什么在您的情况下,a=5打印出6。

在c++中,有称为postfixprefix运算符的运算符,后缀运算符将在语句之后运行,而前缀运算符将在该语句之前运行。

这些运算符将直接影响值。

++前缀运算符,在printf之前得到解析并检索值。

一个++-postfix运算符,检索值,然后在您的printf 之后得到解析

一个-no运算符只检索值。

您可以在此处了解有关这些运算符的更多信息:http://en.cppreference.com/w/cpp/language/operator_incdec

巴斯谢巴,答案是100%正确的。发布这个答案是为了尝试进一步加深你和其他有同样问题的人的理解。

以下是您的代码经过轻微修改,以显示您询问的两个案例。

#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int a;
a = 5;
if(a)   // check whether a is zero (false) or non-zero (true)
{
// variable a has a non-zero value (true)
printf("if %dn" , ++a);  // preincrement variable a then print value
}
else {
// variable a has a value of zero (false)
printf("else %dn" , a);  // print value as it is
}
a = 0;
if(a)   // check whether a is zero (false) or non-zero (true)
{
// variable a has a non-zero value (true)
printf("if %dn" , ++a);  // preincrement variable a then print value
}
else {
// variable a has a value of zero (false)
printf("else %dn" , a);  // print value as it is
}
return 0;
}

使用++a预增加变量和使用++后增加变量是有区别的。

预增量,即++a,增加变量的值,并使新值可用于下一个运算符或操作。

Postincrement,即a++,使变量的当前值可用于下一个运算符或操作,然后递增变量。

因此,请查看以下代码。

int  a;
int  b;
a = 5;
b = a;    // straight assignment, no increment, b now contains 5.
b = a++;  // postincrement a, do assignment, b now contains 5, a contains 6
b = ++a;  // preincrement a, do assignment, b now contains 7, a contains 7

现在,在您的代码中,首先将值5分配给变量a。执行if时,检查a是true(值为非零)还是false(值为零)。由于a等于5,因此该值为非零,因此它采用then路径。

当它执行printf()时,a的值使用预增量进行修改。这意味着首先递增a的值,然后在printf()中使用a的新值。因此,您打印预增量变量a的值,即6打印"if 6"。

如果您使用了后增量,那么a的旧值将在printf()`printing"If 5"中使用。

接下来,将变量a的值设置为零。if检查a是真、非零还是假、零,并且由于a现在是零或假,所以所采用的路径是else。在这个printf()中,您只是打印变量a的值,所以您看到"else 0"。