Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange multi-variable assignment statement in C

I thought I understood assignment operations in C, but I'm trying to learn a bit of graphics programming and I've come across this initialisation statement which has me confused:

/* request auto detection */
int gdriver = DETECT, gmode, errorcode

I've compiled a small working program using the elements and the result seems to be a combination of assignment and declarations. The first variable on the RHS is assigned to the LHS variable, and the rest are declared (but not initialised) to the type of the LHS variable...

#include <stdio.h>

int main(){

    int a = 0;  // Comment out this line and things break
    int d = a, b, c;

    printf("%d %d %d %d", a, b, c, d);

    return 0;
}

Why would you use a line like this which seems to perform 2 unrelated actions together?

like image 907
maccaroo Avatar asked Mar 24 '26 19:03

maccaroo


2 Answers

The declaration

int d = a, b, c;

is functionally identical to

int d = a;
int b;
int c;

The variable d is initialised to the value of a, and b and c are both uninitialised.

like image 93
Greg Hewgill Avatar answered Mar 27 '26 10:03

Greg Hewgill


To answer second part, someone very likely extended an initialised declaration or put the initialiser there later rather than assigning, not caring too much about clarity. When declaring together on one line, for clarity an assignment expression helps :

double x, y, z; x = y = z = 0.0;

So in the example, I'd prefer, if it's clearer than multiple lines :

/* request auto detection */
int gdriver = DETECT; int gmode, errorcode;

Having C11 (or C99) compiler is nice, as you can initialise near usage like C++. In large software engineering projects, I basically found it was almost always better to write, declarations 1 per line (except where variables were intimately coupled), as it was very so common to have to add 1 or 2 more, change a name or type later and 1 per line, allowed you to copy/cut & paste code more regularly, than if you attempted to maintain declaration lists, which would cause wasted time on re-formatting over and over for readability, rather than just lining up columns once for type, identifier and any initialiser.

On comma expressions, Wikipedia has some good examples and points out in declarations "comma acts as a seperator" - Comma operator. It's considered very bad style to use a comma expression inside array subscripts n = foo[ a++, b] for example as it's intent is very misleading to anyone used to notation in other languages or maths.

like image 43
Rob11311 Avatar answered Mar 27 '26 10:03

Rob11311



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!