0
Buffer* b_create(int init_capacity, char inc_factor,char o_mode){

Buffer* buffer=NULL;    /*local pointer to the buffer structure on heap*/ 

if (o_mode=='f' || inc_factor==0){
    o_mode=0;
    inc_factor=0;
}else if (o_mode=='f' && inc_factor!=0){
    o_mode=0;
    inc_factor=0;
}else if (o_mode=='a' && 1<=inc_factor<=255){
    o_mode=1;
    inc_factor=inc_factor;
}else if (o_mode=='m' && 1<=inc_factor<=100){
    o_mode=-1;
    inc_factor=inc_factor;
}
else{
    buffer=NULL;
    return buffer;
}

    //throw a more meaningful error??

    //cleanup :: how about i just call the ca_destroy() ??
    /*
    free(buffer->ca_head);
    buffer->ca_head=NULL;
    free(buffer);
    buffer=NULL;
*/

buffer = (Buffer*)malloc(sizeof(Buffer));
buffer->ca_head=(char*)malloc(sizeof(char)*init_capacity);
buffer->mode=o_mode;
buffer->inc_factor=inc_factor;

buffer->capacity=init_capacity;
buffer->addc_offset=0;
buffer->mark_offset=0;
buffer->r_flag=0;

return buffer;

}

我有上述方法。我正在努力让它工作。首先,我检查并设置了几个变量。如果没有任何情况适用,那么我将缓冲区设置为 NULL 并尝试将值返回给调用函数。

else{
    buffer=NULL;
    return buffer;
}

然而,在返回之后,函数继续并继续创建缓冲区结构。我希望该函数一旦看到返回语句就会退出。为什么它继续执行?

4

1 回答 1

4

这个条件

1<=inc_factor<=255

总是正确的。它被解析为(1 <= inc_factor) <= 255,并1 <= inc_factor评估为 0 或 1。因此,如果o_mode'a''m'之一,则早期条件之一成立,即使inc_factor是 0 或负数。

查看条件链,我们发现:

if (o_mode=='f' || inc_factor==0){
    o_mode=0;
    inc_factor=0;
}else if (o_mode=='f' && inc_factor!=0){ // This is never true, because if o_mode == 'f',
    o_mode=0;                            // the first one already was true
    inc_factor=0;
}else if (o_mode=='a' && 1<=inc_factor<=255){ // This is just o_mode == 'a'
    o_mode=1;
    inc_factor=inc_factor;
}else if (o_mode=='m' && 1<=inc_factor<=100){ // This is just o_mode == 'm'
    o_mode=-1;
    inc_factor=inc_factor;
}
else{ // This is only reached if o_mode is none of 'f', 'a', 'm' and inc_factor is != 0
    buffer=NULL;
    return buffer;
}

但如果o_mode不是'f', 'a', 'm'and ,则达到并返回inc_factor != 0最终结果。没有任何实现被破坏到足以忽略一条语句。elseNULLreturn

于 2012-09-24T22:31:36.727 回答