Which code snippet is more effective.
case 1:
cases 2:Code:char *str;
str = (char *) malloc(15);
if(!str)
return -ENOMEM;
does it effect execution time?Code:char *str;
if(!(str = (char *) malloc(15)))
return -ENOMEM
Printable View
Which code snippet is more effective.
case 1:
cases 2:Code:char *str;
str = (char *) malloc(15);
if(!str)
return -ENOMEM;
does it effect execution time?Code:char *str;
if(!(str = (char *) malloc(15)))
return -ENOMEM
If so, it's negligible. I'd suggest making the decision based on your style preferences. Two things worth noting about these snippets:
* The cast may be omitted, as void *s may be converted to other object pointer types by the = operator in C.
* It's totally fine to use ! or ==0 to check whether str stores a null pointer, but some prefer using ==NULL in this scenario.
No, no difference at all when tested on MSVC compiler at max optimisation.
Here's the disassembly of your first snippet:
And your second:Code:char* test1(void) {
push ebp
mov ebp,esp
sub esp,0CCh
push ebx
push esi
push edi
lea edi,[ebp-0CCh]
mov ecx,33h
mov eax,0CCCCCCCCh
rep stos dword ptr es:[edi]
char *str;
str = (char *)malloc(15);
mov esi,esp
push 0Fh
call dword ptr ds:[0A89114h]
add esp,4
cmp esi,esp
call __RTC_CheckEsp (0A8113Bh)
mov dword ptr [str],eax
if (!str)
cmp dword ptr [str],0
jne test1+3Eh (0A8140Eh)
return str;
mov eax,dword ptr [str]
}
pop edi
pop esi
pop ebx
add esp,0CCh
cmp ebp,esp
call __RTC_CheckEsp (0A8113Bh)
mov esp,ebp
pop ebp
ret
The first is only 1 line longer because of the interleaved source code. Of course, I can't speak for all compilers/instruction sets, but I don't see how a compiler could mess your first example up. And as zyxwvuts said, if there is any difference on any platform it'd be negligible.Code:char* test2(void) {
push ebp
mov ebp,esp
sub esp,0CCh
push ebx
push esi
push edi
lea edi,[ebp-0CCh]
mov ecx,33h
mov eax,0CCCCCCCCh
rep stos dword ptr es:[edi]
char *str;
if (!(str = (char *)malloc(15)))
mov esi,esp
push 0Fh
call dword ptr ds:[0A89114h]
add esp,4
cmp esi,esp
call __RTC_CheckEsp (0A8113Bh)
mov dword ptr [str],eax
cmp dword ptr [str],0
jne test2+3Eh (0A8147Eh)
return str;
mov eax,dword ptr [str]
}
pop edi
pop esi
pop ebx
add esp,0CCh
cmp ebp,esp
call __RTC_CheckEsp (0A8113Bh)
mov esp,ebp
pop ebp
ret
On the subject of ! or 0 or NULL.... MISRA insists that you use NULL. In fact, you're meant to use != 0 for testing variables in conditionals, lest some poor soul be confusied..... it's an insane piece of literature. Made me laugh out loud at some points.
I personally find your first snippet clearer. And I have a preference for NULL over 0.
Yes, in terms of efficiency they will almost certainly be compiled to the same code. Like smokeyangel, I find the former to be more readable. As zyxwvuts noted, you should get rid of the cast of the return value of malloc (unless you are specially writing your code to be compilable as C++ too).