Search code examples
cdeclarationreadabilitycode-readability

Does not declaring more than one variable in one declaration makes the code more readable?


When someone has a lot of variables, is it better to declare all the variables of the same type in one line or write one line for each variable declaration? (in terms of readability of the code)

for example

All in one line :

       int my_rank, comm_size, processors_used, name_length, *x, *y;
       double mean_value, variance, var_sum, *var_sums;
       char string,*tmp,option;

Each on its own line:

    int my_rank;
    int comm_size;
    int processors_used;
    int name_length;
    int *x;
    int *y;
    double mean_value;
    double variance;
    double var_sum;
    double *var_sums;
    char string;
    char *tmp;
    char option;

I would prefer the first over the second but i'm in a situation where i simply have about 19 integers and i think that either way makes the code look illegible and ugly.

I actually separated the declarations in logical blocks and grouped variables in the same declaration if they are correlated.

int my_rank, comm_size, processors_used, name_length;
int *x, *y, *send_counts, *displacement, num; 
int max, min, loc_max, loc_min, *max_array, *min_array;
int i,option,sum,*sums;
double mean_value, variance, var_sum, *var_sums, *delta_vector, *local_delta;
char proc_name[MPI_MAX_PROCESSOR_NAME];
MPI_Status status;

Which do you think makes the code more readable?


Solution

  • It is mostly a matter of opinion whether you group definitions for local variables or separate them one per line. Here are some general remarks:

    • Local coding style may impose one over the other. Consistency with the rest of the project is valuable and helps readability.

    • Documenting some of these definitions with a short comment on the same line may be useful and prompts for separating them. Yet do not comment the obvious.

    • If you group definitions in logical blocks, do not mix pointers and variables on the same line. It is confusing to many readers.

    • Moving the definitions closer to where the variables are used also helps readability as it reduces the scope for these variables are reduces mental space as well, a limited resource.