The first one is especially bad, but both incur in arguably bad practices. If at all possible, you shouldn't use return except as the very last line in a function. The reason for this is that return, like break or goto, bypasses normal execution flow and makes code paths harder to follow.
I would use:
Code:
function doThing() {
return condition ? 1 : 2;
}
Or if the language doesn't support the ? : operator:
Code:
function doThing() {
int ret;
if (condition) {
ret = 1;
} else {
ret = 2;
}
return ret;
}
By the way, in the second example, leaving ret uninitialized helps catch potential situations where you don't set a correct value to it, since modern IDEs will display an error or warning that you're returning a potentially uninitialized value. E.g. this will display an error / warning:
Code:
function doThing() {
int ret;
if (condition) {
ret = 1;
} else if (condition2) {
ret = 2;
}
return ret;
}
Of course, if your IDE doesn't warn about uninitialized values, then the safest option is to initialize it to a valid default value at the beginning.
B is better (less error prone in the long run) than A.
But usually I don't do returns in the middle of a function, so it's this instead:
Hahah, beaten by a minute. But yeah, exactly this.