Simple question about if-else statement.

Hi!
Is there any difference between these two codes? I mean, which one is more correct considering good programming practice or something else?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int anyFunctionName( ) {
	//...
	if(x > y)
		return y;
	else
		return x;
}

or

int anyFunctionName( ) {
	//...
	if(x > y)
		return y;

return x;
}
Nope, it's the same.

About the style: I guess the first version is considered better in terms of good programming practice.

It is also a bit cleaner in this case.

However, I personally would use the second version, because I consider the return y; an escape and the return x; the actual default function exit.
If you want to return the smaller of x and y I think you should pass the values to std::min and return the value. That way the code clearly shows what you are doing and you minimize the chance of making a mistake while writing those if statement.
 
return std::min(x, y);

Otherwise, in situations like this, you might want to use the conditional operator.
 
return x > y ? y : x;
If you want to return the smaller of x and y I think you should pass...


No, is just an example to illustrate my question. But thanks for your answer.
Topic archived. No new replies allowed.