Skip to contentSkip to conversation

checkpatch: Add 'Prefer ARRAY_SIZE" test

PATCH New Joe Perches 1 participant 1 message Apr 7, 2015 Checkpatch

lore
Share & tools
lore

Joe Perches

author maintainer
#0 lore raw

PATCH 1/1 checkpatch: Add 'Prefer ARRAY_SIZE" test

Add a test for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo).

---
 scripts/checkpatch.pl | 13 +++++++++++++
 1 file changed, 13 insertions(+)
scripts/checkpatch.pl +13 -0
index 9a8b2bd..d2e9752 100755
@@ -3226,6 +3226,19 @@ sub process {
 				$herecurr);
                }
 
+# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
+		if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
+			my $array = $1;
+			if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
+				my $array_div = $1;
+				if (WARN("ARRAY_SIZE",
+					 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
+				    $fix) {
+					$fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
+				}
+			}
+		}
+
 # check for function declarations without arguments like "int foo()"
 		if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
 			if (ERROR("FUNCTION_WITHOUT_ARGS",