在此 C 代码中如何进行转换?
How is the conversion being done in this C code?
#include<stdio.h>
#include<string.h>
void printlength(char *s, char *t) {
unsigned int c=0;
int len = ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t);
printf("%d\n", len);
}
void main() {
char *x = "abc";
char *y = "defgh";
printlength(x,y);
}
当我编译它时,它给出 3,但是,我不明白这里是如何进行转换的:(strlen(s) - strlen(t)) > c)
这是非常糟糕的代码 (strlen(s) - strlen(t))
总是 >= 0 因为它是无符号数学。 strlen()
返回的类型是 size_t
,一些无符号类型。因此,除非值相等,否则由于无符号数学环绕,差值始终为正数。
然后 int len = strlen(s);
即使 s
的长度与 t
不同。
使用类似代码的更好方法是仅添加。
// ((strlen(s) - strlen(t)) > c)
(strlen(s) > (c + strlen(t))
注意:在具有 SIZE_MAX <= INT_MAX
的罕见平台上,差异可能是负数,因为数学是使用 signed 类型 int
完成的。然而与 c
的比较是 unsigned
然后发生 unsigned
导致负差异 "wrapped-around" 到一个非常大的数字,大于 0。
#include<stdio.h>
#include<string.h>
void printlength(char *s, char *t) {
unsigned int c=0;
int len = ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t);
printf("%d\n", len);
}
void main() {
char *x = "abc";
char *y = "defgh";
printlength(x,y);
}
当我编译它时,它给出 3,但是,我不明白这里是如何进行转换的:(strlen(s) - strlen(t)) > c)
这是非常糟糕的代码 (strlen(s) - strlen(t))
总是 >= 0 因为它是无符号数学。 strlen()
返回的类型是 size_t
,一些无符号类型。因此,除非值相等,否则由于无符号数学环绕,差值始终为正数。
然后 int len = strlen(s);
即使 s
的长度与 t
不同。
使用类似代码的更好方法是仅添加。
// ((strlen(s) - strlen(t)) > c)
(strlen(s) > (c + strlen(t))
注意:在具有 SIZE_MAX <= INT_MAX
的罕见平台上,差异可能是负数,因为数学是使用 signed 类型 int
完成的。然而与 c
的比较是 unsigned
然后发生 unsigned
导致负差异 "wrapped-around" 到一个非常大的数字,大于 0。