在遇到第一个return语句时函数执行没有退出

时间:2012-09-24 22:28:27

标签: c return return-value

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;
}

然而,在返回之后,该函数继续并继续并且无论如何都会创建缓冲区结构。我希望函数在看到return语句后退出。为什么它会继续执行??

1 个答案:

答案 0 :(得分: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'inc_factor != 0,则会到达最终else并返回NULL。没有足够的实现可以忽略return语句。