mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH] checkpatch: warn on unnecessary else after return or break
@ 2014-06-09  4:11 Joe Perches
  0 siblings, 0 replies; only message in thread
From: Joe Perches @ 2014-06-09  4:11 UTC (permalink / raw)
  To: Andrew Morton; +Cc: Andy Whitcroft, LKML

Using an else following a break or return can unnecessarily
indent code blocks.

ie:
	for (i = 0; i < 100; i++) {
		int foo = bar();
		if (foo < 1)
			break;
		else
			usleep(1);
	}

is generally better written as:

	for (i = 0; i < 100; i++) {
		int foo = bar();
		if (foo < 1)
			break;
		usleep(1);
	}

Warn when a bare else statement is preceded by a
break or return indented 1 tab more than the else.

Signed-off-by: Joe Perches <joe@perches.com>
---
 scripts/checkpatch.pl | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/scripts/checkpatch.pl b/scripts/checkpatch.pl
index 010b18e..9059fd0 100755
--- a/scripts/checkpatch.pl
+++ b/scripts/checkpatch.pl
@@ -2342,6 +2342,16 @@ sub process {
 # check we are in a valid C source file if not then ignore this hunk
 		next if ($realfile !~ /\.(h|c)$/);
 
+# check indentation of any line with a bare else
+# if the previous line is a break or return and is indented 1 tab more...
+		if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
+			my $tabs = length($1) + 1;
+			if ($prevline =~ /^\+\t{$tabs,$tabs}(?:break|return)\b/) {
+				WARN("UNNECESSARY_ELSE",
+				     "else is not generally useful after a break or return\n" . $hereprev);
+			}
+		}
+
 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
 		if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
 			WARN("CONFIG_EXPERIMENTAL",



^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2014-06-09  4:11 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2014-06-09  4:11 [PATCH] checkpatch: warn on unnecessary else after return or break Joe Perches

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®