-1

I am new to coding, and my team mates mentioned that I should not declare more than one variable in a single line. I code in C, and I noticed alot of documentation doing that, i.e:

int i, j, k;

is there a real reason behind declaring in a single line sometimes and other times not?

on the other side, I tend to declare each variable in a single line to initialise it, can i do that with several variables and not run into problems?

I use gcc compiler.

sarah
  • 135
  • 5
  • 1
    This is more of a opinion based question. Your team chooses a style for declaring one variable in a line to identify if someone forgot to initialize it. – Louis Go Aug 25 '20 at 01:43
  • By declaring multiple variables in a single line, you save the typing of type mutiple times. In my opinion, the con of single line declaration is huge when it comes to [pointers](https://stackoverflow.com/a/3247313/4123703). – Louis Go Aug 25 '20 at 01:46
  • A worse issue is that of single-letter variable names:( – Martin James Aug 25 '20 at 02:04
  • @MartinJames But `i, j, k` is okay for raw loops or matrix. – Louis Go Aug 25 '20 at 02:06
  • Using a separate declaration per variable makes it easy to add or remove variables as necessary - you just insert or remove a line. It can also improve readability if you're declaring a mix of regular variables, pointers, and arrays - a line like `int a[N], *p, f(void);` can be a little eye-stabby. There's a C++ convention of declaring pointers as `T* p;` (which I've ranted about elsewhere), so if you write `T* p, q;`, it looks like you may be intend for both `p` and `q` to be pointers, but only `p` will be. Making those separate declarations makes the intent clearer. – John Bode Aug 25 '20 at 14:17

1 Answers1

0

It's more of an opinion base, but I post an answer for readibility. Declaring in a single line has pros and cons.

Pros

  • Save typing for multiple times. For int i, j , k you saved twice of int.

Cons

  • Forgot to initialize or assign it. Like int i, j, k = 0...opps only k has value.
  • Pointer declarations int* i, j , k where there is only i is pointer. Details here.

For more details, you may refer to other C guidelines.

Also I found SEI CERT C Coding Standard confluence wiki seems good to read.

Louis Go
  • 2,213
  • 2
  • 16
  • 29