if()里面的赋值语句

  • 在java中if里面最终结果必须要是boolean类型,所以可以有赋值语句,但必须是布尔类型之间的赋值,如果是其他类型则会报错。
public class ife {
    static boolean a;// 静态方法不能访问非静态变量
    public static void main(String[] args) {
        boolean x = true;
        if (a = x) {
            System.out.print("hello");
        } else {
            System.out.print("hi");
        }
    }
}
------------结果:
hello
Process finished with exit code 0

public class ife {
    public static void main(String[] args) {
        int x = 0;
        int a = 1;
        if (a = x) {
            System.out.print("hello");
        } else {
            System.out.print("hi");
        }
    }
}
-----结果:
Error:(7, 15) java: 不兼容的类型: int无法转换为boolean


  • 在c语言中,如果最终结果是int类型,则会与0进行比较,大于0,返回true,小于0,返回false。
#include <stdio.h>
int main(){
	int x = 5;
	int a = 0;
	int b = 0;
	if (x = a + b) {
		printf("*****\n");	
	} else {
		printf("#####\n");
	}
}
-------结果:
#####
#include <stdio.h>
int main(){
	if (3) {
		printf("*****\n");	
	} else {
		printf("#####\n");
	}
}
---结果:
#####
发布了56 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/hpccph15/article/details/85237245