Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma in variable initialization/declaration

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?

like image 680
Yoav Avatar asked Sep 08 '14 08:09

Yoav


People also ask

What is correct way to declare and initialize variable?

When you declare a variable, you should also initialize it. Two types of variable initialization exist: explicit and implicit. Variables are explicitly initialized if they are assigned a value in the declaration statement. Implicit initialization occurs when variables are assigned a value during processing.

Can variables have commas?

Each variable is separated by a comma ( , ), and the last variable ends with a semicolon (;) which terminates the var statement.

What is the syntax of variable initialization?

Basic Syntaxint a, b, c; // declare 3 variables. int z = 35; // declare and initialize variable z with value 35.

What is variable declaration example?

a) General syntax for declaring a variable Eg:- char Final_Grade; // Final_Grade is a variable of type char, and no value is assigned to it. data_type variable_name = val; Eg:- int age = 22; // age is a variable of type int and holds the value 22. Here, data_type specifies the type of variable like int, char, etc.


1 Answers

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.

like image 158
Marc Gravell Avatar answered Sep 27 '22 21:09

Marc Gravell