Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable as locally as possible

I'm new to Linux kernel development.

One thing that bothers me is a way a variables are declared and initialized.

I'm under impression that code uses variable declaration placement rules for C89/ANSI C (variables are declared at the beginning of block), while C99 relaxes the rule.

My background is C++ and there many advises from "very clever people" to declare variable as locally as possible - better declare and initialize in the same instruction:

  • Google C++ Style Guide
  • C++ Coding Standards: 101 Rules, Guidelines, and Best Practices - item 18
  • A good discussion about it here.

What is the accepted way to initialize variables in Linux kernel?

like image 291
dimba Avatar asked Aug 25 '11 09:08

dimba


People also ask

How do you declare a local variable in C++?

A variable defined inside a function (defined inside function body between braces) is called a local variable or automatic variable. Its scope is only limited to the function where it is defined. In simple terms, local variable exists and can be accessed only inside a function.

What is an example of a local variable?

For example: for(int i=0;i<=5;i++){……} In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.

Are variables declared in main local?

If you declare any variable within any method, it is a local variable. Your main might be a special method, but it is a method. Therefore, anything you declare in your main will be a local variable as well.


2 Answers

I couldn't find a relevant passage in the Linux kernel coding style. So, follow the convention used in existing code -- declare variables at beginning of block -- or run the risk of your code seeming out-of-place.

Reasons why variables at beginning of block is a Good Thing:

  • the target architecture may not have a C99 compiler
  • ... can't think of more reasons
like image 181
pmg Avatar answered Sep 18 '22 00:09

pmg


You should always try to declare variables as locally as possible. If you're using C++ or C99, that would usually be right before the first use.
In older C, doing that doesn't fall under "possible", and there the place to declare those variables would usually be the beginning of the current block.

(I say 'usually' because of some cases with functions and loops where it's better to make them a bit more global...)

like image 33
Eran Zimmerman Gonen Avatar answered Sep 22 '22 00:09

Eran Zimmerman Gonen