I took a course in C++ where we had some homework to show to our teacher, in there were some if statements like this:
if (A != 10)
return 1;
...snip logic ...
return 12;
He didn’t like this and suggested i’d neste it like this instead, even if there was more than one level of nesting:
if (A == 10) {
...snip logic ...
return 12;
} else
return 1;
He couldn’t really explain to me why he wanted it like that. So my question is, is there any reason to nestle if statements like that? I think it’s both easier and cleaner to have some conditions in the beginning of my function which return early. Any thoughts or ideas on why one of these ideas is better/faster? Is there any big difference in the compiled code afterwards?
When it comes to coding style you can listen to opinions but it’s best that you make your own style. The first solution looks far cleaner to me, easier to read, but it’s just a matter of taste after all.
In regard to performance there’s absolutely no difference.