背景
- 我的看家本领是java,做的是android研发;
- 在看C++/C 的代码时总是会看到不同于java的if条件语句 没有判断 true 和 false 的痕迹,但是能编译,能运行:
int a = 0;
if (a) {
cout << "handle the 0" <<endl;
} else {
cout << "handle the 0 in else " << endl;
}
- 和java是不是有些不一样?🤪🤪🤪🤪🤪
先说结论
- 当if(expression) expression 的值不为0 时,就会走if里的语句,反之走 else或者 走下一个else if();
- 至于为啥这样? 个人感觉:和C,Linux API 有关吧
- 举个🌰栗子,我们在Linux环境下创建一个socket,
- man socket 一下:
- 看,返回值是一个 int 值,看看api怎么解释;
int 是-1的,就代表,否则,这个int值就表示 socket的文件描述符 fd;
写个demo
-
主要测试以下条件:
* 0 * 大于0 * 小于0 * 在if条件语句里进行赋值操作
int main() {
int a = 0;
if (a) {
// 不会走
cout << "handle the 0" << std::endl;
} else {
// 会走
cout << "handle the 0 in else " << endl;
}
a = 1;
if (a) {
// 会走
cout << "handle the 1" << endl;
}
a = -1;
if (a) {
// 会走
cout << "handle the -1" << endl;
}
// 赋值操作
if (a = 2000) {
// 会走
cout << "handle the 2000" << endl;
}
// 赋值操作
if (a = 0) {
// 不会走
cout << "handle the 0 by else again...." << endl;
} else {
// 会走
cout << "handle the non-0 by else again...." << endl;
}
return 0;
}
- 结果