CODING_STYLE: update with a better description for variable assignments

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>
This commit is contained in:
Peter Hutterer 2022-06-21 15:11:08 +10:00
parent 68f39925ed
commit 3475850084

View file

@ -52,19 +52,18 @@ somenamethatiswaytoolong(int a,
- if it generates a static checker warning, it needs to be fixed or - if it generates a static checker warning, it needs to be fixed or
commented commented
- declare variables before they are used, try to keep them as local as possible. - declare variables when they are used first and try to keep them as local as possible.
Exception: if the same variable is re-used in multiple blocks, declare it Exception: basic loop variables, e.g. for (int i = 0; ...) should always be
at the top. declared inside the loop even where multiple loops exist
Exception: basic loop variables, e.g. for (int i = 0; ...)
```c ```c
int a; int a;
if (foo) { if (foo) {
int b; int b = 10;
a = get_value(); a = get_value();
usevalue(a); usevalue(a, b);
} }
if (bar) { if (bar) {
@ -76,29 +75,79 @@ int c = a * 100;
useit(c); 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: wrong:
```c ```c
{ int *a;
int a = foo();
int b = 7; int b = 7;
}
... some code ...
a = zalloc(32);
``` ```
right: right:
```c
int b = 7;
... some code ...
int *a = zalloc(32);
```
- avoid calling non-obvious functions inside declaration blocks for multiple
variables.
bad:
```c ```c
{ {
int a; int a = 7;
int b = 7; int b = some_complicated_function();
int *c = zalloc(32);
a = foo();
} }
``` ```
There are exceptions here, e.g. `tp_libinput_context()`, better:
`litest_current_device()` ```c
{
int a = 7;
int *c = zalloc(32);
int b = some_complicated_function();
}
```
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 - 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 statement. If either if or else block are multiple statements, both must