10

I've stumbled upon a piece of code that look as follows:

    void check()
    {
        int integer = 7;

        //integer2 is not declared anywhere
        int check = integer, integer2;

        //after running
        //check = 7
        //integer = 7
        //integer2 = 0
    }

what's the purpose of the comma here?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Yoav
  • 3,326
  • 3
  • 32
  • 73

1 Answers1

11

Comma on variable declarations simply allows you to declare a second variable of the same type. It is equivalent to:

int check = integer;
int integer2;

As for:

//integer2 is not declared anywhere

Yes it is; right here! This is the declaration of integer2.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    I knew I can do this: `int integer1, integer2, integer3;` but not that this can be used both for declaration and initialization. Doesn't look like a feature id like to use since it might be misleading... Thanks anyway :) – Yoav Sep 08 '14 at 08:40
  • @Yoav actually, I use it lots; a classic usage is in stream IO: `int offset = 0, count; while((count = source.Read(buffer, offset, buffer.Length)) > 0) { offset += count; ... }` – Marc Gravell Sep 08 '14 at 08:42
  • surprisingly (or not) the place I originally ran into this code is here: http://stackoverflow.com/a/3967595/1092181 – Yoav Sep 08 '14 at 08:44
  • @Yoav see, I told you I used it ;p – Marc Gravell Sep 08 '14 at 08:57