0%

隐式类型转换导致的诡异bug

看以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
NSUInteger a = 100;
NSUInteger b = 104;
NSUInteger c = 30;
NSInteger ret = a - b;
if (ret > c) { //ret被隐式转换为无符号整型
NSLog(@"1");
}
if (ret > (NSInteger)c) {
NSLog(@"2");
}
NSLog(@"ret:%ld", (long)ret);
NSLog(@"ret:%lu", (unsigned long)ret);

打印:

1
2
3
2023-04-30 13:10:02.474708+0800 PodDemo[22390:3868894] 1
2023-04-30 13:10:02.474798+0800 PodDemo[22390:3868894] ret:-4
2023-04-30 13:10:02.474845+0800 PodDemo[22390:3868894] ret:18446744073709551612

po 与 p:对象最好使用po,基础数据类型使用p。

swift则会溢出崩溃:swift直接写上面的代码编译都通不过,得拐个弯:

1
2
3
4
5
6
7
8
9
10
11
12
func myoverflow() {
let a: UInt64 = 100
let b: UInt64 = 103
_myoverflow(a, b)
}
func _myoverflow(_ a: UInt64, _ b: UInt64) {
let ret = a - b //Thread 1: Swift runtime failure: arithmetic overflow
let c: Int = 30
if ret > c {
print("sd")
}
}

swift确实是一门安全的语言。

觉得文章有帮助可以打赏一下哦!