Search code examples
c++cvariablesinitializationcomma-operator

Comma as separator in variable initialization (not as operator)


This seems such a simple question, but something I've not examined for ages in my own style... When initializing variables separated by a comma, I've assumed the following to be an unsafe practice:

unsigned int n = foo.size, nxn = n * n;

Since I don't really ever use the comma operator as such for syntactic sugar, etc; but rather to indicate that two expressions are independent - as a kind of implicit commentary on 'fine-grained parallelism' (or expression independence), that often makes code a bit more terse, e.g.,

if (<some condition>)
    a = true, b = value;

rather than requiring {} scope for semi-colon separated expressions.

But my question is really in re-examining the variable initialization case. Have I been incorrect in my assumption that nxn can't be relied on to be initialized as expected? Or have I been laboring under a misinterpretation all this time?


Solution

  • Per [dcl.decl]/3

    Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself. [...]

    we get that

    unsigned int n = foo.size, nxn = n * n;
    

    is the same as

    unsigned int n = foo.size;
    unsigned int nxn = n * n;
    

    There is a note with exceptions for other rules like auto or if a name shadows the type but those don't apply in this case.


    Be very wary with pointers if you put multiple variables on a single line

    int * foo, bar;
    

    does not give you two pointers. Instead, foo is a pointer and bar is an int. You would need

    int * foo, * bar;
    

    to get two pointers. For this reason I would prefer to use

    int * foo;
    int * bar;
    

    and pay the extra keystorkes for safeties sake.