CODING_STYLE: update with a better description for variable assignments
authorPeter Hutterer <peter.hutterer@who-t.net>
Tue, 21 Jun 2022 05:11:08 +0000 (15:11 +1000)
committerPeter Hutterer <peter.hutterer@who-t.net>
Wed, 29 Jun 2022 04:37:58 +0000 (14:37 +1000)
Loop variables shouldn't be re-used.

Avoid uninitialized variables

Sort variables to make function calls more obvious

Signed-off-by: Peter Hutterer <peter.hutterer@who-t.net>
CODING_STYLE.md

index cc7bdc2..5358233 100644 (file)
@@ -52,19 +52,18 @@ somenamethatiswaytoolong(int a,
 - if it generates a static checker warning, it needs to be fixed or
   commented
 
-- declare variables before they are used, try to keep them as local as possible.
-  Exception: if the same variable is re-used in multiple blocks, declare it
-  at the top.
-  Exception: basic loop variables, e.g. for (int i = 0; ...)
+- declare variables when they are used first and try to keep them as local as possible.
+  Exception: basic loop variables, e.g. for (int i = 0; ...) should always be
+  declared inside the loop even where multiple loops exist
 
 ```c
 int a;
 
 if (foo) {
-        int b;
+        int b = 10;
 
         a = get_value();
-        usevalue(a);
+        usevalue(a, b);
 }
 
 if (bar) {
@@ -76,29 +75,79 @@ int c = a * 100;
 useit(c);
 ```
 
-- do not mix function invocations and variable definitions.
+- avoid uninitialized variables where possible, declare them late instead.
+  Note that most of libinput predates this style, try to stick with the code
+  around you if in doubt.
 
   wrong:
 
 ```c
-{
-        int a = foo();
+        int *a;
         int b = 7;
-}
+
+        ... some code ...
+
+        a = zalloc(32);
 ```
 
   right:
+
 ```c
-{
-        int a;
         int b = 7;
+        ... some code ...
+
+        int *a = zalloc(32);
+```
+
+- avoid calling non-obvious functions inside declaration blocks for multiple
+  variables.
+
+  bad:
+
+```c
+{
+        int a = 7;
+        int b = some_complicated_function();
+        int *c = zalloc(32);
+}
+```
 
-        a = foo();
+  better:
+```c
+{
+        int a = 7;
+        int *c = zalloc(32);
+
+        int b = some_complicated_function();
 }
 ```
 
-  There are exceptions here, e.g. `tp_libinput_context()`,
-  `litest_current_device()`
+  There is a bit of gut-feeling involved with this, but the goal is to make
+  the variable values immediately recognizable.
+
+- Where statements are near-identical and repeated, try to keep them
+  identical:
+
+  bad:
+```c
+int a = get_some_value(x++);
+do_something(a);
+a = get_some_value(x++);
+do_something(a);
+a = get_some_value(x++);
+do_something(a);
+```
+  better:
+
+```c
+int a;
+a = = get_some_value(x++);
+do_something(a);
+a = get_some_value(x++);
+do_something(a);
+a = get_some_value(x++);
+do_something(a);
+```
 
 - if/else: { on the same line, no curly braces if both blocks are a single
   statement. If either if or else block are multiple statements, both must