我的IF情况表现得很奇怪,HELP C.

时间:2014-10-29 19:45:59

标签: c if-statement conditional-statements mean

我的病情有问题:

if(pos + strlen(string) > 0){
    printf("#");
    string = &string[pos*-1];               
    pos = 0;                
}
程序中的

void text_buffer(bool strict, int x, int y, char *string){
    if(active_buff){
        int pos = active_buff -> width * y + x;

        if(pos < 0){
            int cnt = strlen(string) + pos;
            printf("%d %s", cnt, cnt > 0 ? "true" : "false");

            if(pos + strlen(string) > 0){
                printf("#");
                string = &string[pos*-1];               
                pos = 0;                
            }

            else
                return;
        }
        if(pos >= active_buff -> length - 1)
            return;
        char *copy = &(active_buff -> buff[pos]);
        if(strict)
            for(; x < active_buff -> width && *copy && *string; copy++, string++, x++)
                *copy = *string;
        else
            for(; *copy && *string; copy++, string++)
                *copy = *string;
    }
}

例如:当我传递长15个字符的文本“Hello World!99”并且变量'pos'被计算为-2000时,我提到的那个条件将是值true。

但是,如果我将(pos + strlen(string))存储到变量'cnt'而不是计算条件,那么它的值为'false'。

我不知道,我试过将(pos + strlen(string))放入括号中,如果有条件,但仍然没有运气。

1 个答案:

答案 0 :(得分:1)

如果pos-2000(正如您在问题中所述)那么条件中的表达式为:

if(pos + strlen(string) > 0) {...}

将是一个非常大的数字(确切的值取决于您平台上size_t的宽度)并且将成立。

这是因为您要添加一个带有无符号整数的intstrlen()返回size_t),这会导致无符号整数类型并且总是会运行大于或等于零。

你可以这样做:

if(pos + (int)strlen(string) > 0)  {...}