same operation in multiple if statement, how to reduce code redundancy

作者在一次面试中被要求减少代码中的冗余,并尝试了几种不同的解决方案。本文探讨了如何通过重构来优化代码结构,减少重复的内存释放操作,并提供了一种使用循环结构的可能方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm using Linux, and don't want to install Chinese input method, so I'm going to write this diary in English.

Server days ago, I was asked to reduce code redundancy (see below) in a job interview.

char *a = (char*)malloc(100*sizeof(char));
if(doSomething1(a))
   free(a);
   return;
if(doSomething2(a))
   free(a);
   return;
if(doSomething3(a))
   free(a);
   return;
free(a);
return

Out of nervous, I just came up with this:

if (doSomething1(a) || doSomething2(a) || doSomething3(a))
   ;
free(a);
return;

However, I was told this doesn't fit into situation where additional operation specified to doSomething1() is required, e.g.

if(doSomething1(a))
   foo;
   free(a);
   return;
if(doSomething2(a))
   free(a);
   return;
So I post a question on stackoverflow, and got nice answers specified to c++. Just now I came up with this:

while(True)
   if (doSomething1(a))
      foo;
      break;
   if (doSomething2(a))   break;
   if (doSomething3(a))   break;
   break;
free(a);
return;

However, I was told in the interview that there are at least five ways for this. Do you have an idea?


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值