深入理解计算机系统 练习题2.26 答案与分析

测试代码

#include <stdio.h>  
#include "stdafx.h"
#include <iostream>


using namespace std;

int strlonger(char *s, char *t) {
    return strlen(s) - strlen(t)>0;
}
int main() {

    char *s = "abc";
    char *t = "abcd";

    int c = strlonger(s, t);
    cout << c << endl;

}

A.这道题答案说的很清楚,由于strlen采用无符号数,因为无符号数减法肯定还是无符号数不存在负数,所以所有判断都是大于0的,所以出现问题
B.原因通A
C.修改代码如下

#include <stdio.h>  
#include "stdafx.h"
#include <iostream>


using namespace std;

int strlonger(char *s, char *t) {
    return strlen(s) > strlen(t);
}
int main() {

    char *s = "abc";
    char *t = "abcd";

    int c = strlonger(s, t);
    cout << c << endl;

}

猜你喜欢

转载自blog.csdn.net/ciqingloveless/article/details/82740474