else dangling

When using nested if statements, be careful with dangling else. for example:

if (x == 0)
	if (y == 0)
		return 0;
else
	return -1;	

Which if statement does the above else clause belong to? The indented format implies that it belongs to the outermost if statement. However, according to the rules of the C language, the else clause should belong to the closest if statement that has not yet matched any other else. So the else clause actually belongs to the innermost if statement, and the correct indentation should be like this:

if (x == 0)
		if (y == 0)
			return 0;
		else
			return -1;

To make the else clause belong to the outermost if statement, we can enclose the inner if statement with { }:

if (x == 0)
{
	if (y == 0)
		return 0;	
}
else
	return -1;

Guess you like

Origin blog.csdn.net/qq_54880517/article/details/123140669