Skip to main content
gamedev.net
🔒 Locked

Break or return 0;

Started by Leadorn 5 replies 200+ views
Original Post
Leadorn
Leadorn
Hail I was wondering why some people use return 0; in case statements and some people use break; What is the difference between return 0; and break overall. I cant use break to return values but I can use return 0 in switch cases. Is there a correct way? In my book Windows programming by Charles petzold he uses at first return 0; but sometimes he uses break;
IndirectX
IndirectX
break transfers execution to the line immediately following the switch statement. return quits the function. If you have a function consisting of only a switch statement, any way is acceptable, choose any based on your preference. I suspect that break will generate smaller code (only one epilog) while return will generate slightly faster code (no jumps). I would expect the compiler to generate code to effectively use either break or return regardless of what you write if you turn speed/size optimizations on.
---visit #directxdev on afternet <- not just for directx, despite the name
Leadorn
Leadorn
So the correct is to use return 0 in winproc...

Because winproc only handle one message at the time. It would be unnessisery to check the other casees if one case already is true.

Right?
IndirectX
IndirectX
Not exactly. Break will quit the switch immediately, without checking for other messages. I prefer this style:

  
switch (msg) {
case WM_MESSAGE:
DoStuff();
break;
case WM_OTHER_MESSAGE:
DoMoreStuff();
break;
default:
return DefWindowProc(...);
}
return 0;

If msg == WM_MESSAGE, the code checking whether msg == WM_OTHER_MESSAGE will never be executed.
---visit #directxdev on afternet <- not just for directx, despite the name
Leadorn
Leadorn
Yes but i have switches inside the switch(msg) so i will use return 0 in all my winproc because im only handeling one message. Its stupid to check the other cases if one already is true.......or am i wrong.

IndirectX
IndirectX
The statement executed after break is the one right after the switch statement. Nothing is done inside the switch after the break. If this answer doesn''t satisfy you, post some of your code.
---visit #directxdev on afternet <- not just for directx, despite the name
superpig
superpig
In the case of a WNDPROC, it''s usually ok to use "return 0" because you''re never doing anything after the switch.

Be aware that not all messages expect a ''0'' back.

Superpig
- saving pigs from untimely fates
- sleeps in a ham-mock at www.thebinaryrefinery.cjb.net
Richard "Superpig" Fine - saving pigs from untimely fates - Microsoft DirectX MVP 2006/2007/2008/2009
"Shaders are not meant to do everything. Of course you can try to use it for everything, but it's like playing football using cabbage." - MickeyMouse

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.