From: Peter Hutterer Date: Tue, 21 Jun 2022 05:11:08 +0000 (+1000) Subject: CODING_STYLE: update with a better description for variable assignments X-Git-Tag: 1.22.0~53 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=3475850084c0fec670f1eeaa1e1fe966745dbd33;p=platform%2Fupstream%2Flibinput.git 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 --- diff --git a/CODING_STYLE.md b/CODING_STYLE.md index cc7bdc27..53582333 100644 --- a/CODING_STYLE.md +++ b/CODING_STYLE.md @@ -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