-
Type: Improvement
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: None
-
StorEng - Defined Pipeline
Introduction
Traditionally in C, variables are often declared at the beginning of a block or function and WiredTiger's style guide follows it. However, this proposal suggests adopting a style where variables are declared at the point of use, i.e., as close as possible to where they are first needed.
Rationale
- Readability and Maintenance: The code is more readable as the declarations are close to where the variables are used. It also reduces the need to scroll or search to find variable declarations, making the code easier to understand and maintain.
- Scope Minimization: Minimizing the scope of variables helps in reducing errors and unintended side effects.
- Error Reduction: It reduces the risk of using uninitialized variables and helps in preventing errors related to variable scope and lifetime.
- Improved Maintenance: The code is easier to maintain and modify as the variable declarations are located where they are most relevant.
- Potential Stack Optimization: The compiler may optimize stack usage by reusing memory locations for variables in different sub-scopes.
Proposed Style
Variables should be declared at the point of use, i.e., immediately before their first use, rather than at the beginning of the function or block. This ensures that the variable is declared in the smallest possible scope.
Example:
Instead of:
void fn(int a, int b) { int result; int temp; // ... if (x) { temp = a * b; result = temp + a; fn2(result); } // ... }
use:
void fn(int a, int b) { // ... if (x) { int temp = a * b; int result = temp + a; fn2(result); } // ... }
Exceptions
Variables can be declared prior to their use, including the beginning of the block or function:
- Function-wide Variables like ret, variables used multiple times across the function and ones used in macros.
- Code Clarity: If it improves the code clarity.