Jerry213
Jerry213

Reputation: 81

C++ array declaration

     int arr[] = {12, 34, 54, 2, 3}, i;

Happened to see an array declared this way, source here: https://www.geeksforgeeks.org/shellsort/ What does the ,ipart mean? It doesn't seem to do anything yet compiles.

Upvotes: 1

Views: 278

Answers (7)

Kartik Maheshwari
Kartik Maheshwari

Reputation: 357

 int arr[] = {12, 34, 54, 2, 3}, i; 

In this case it will give warning C4101: 'i' : unreferenced local variable. If you want to declare and initialize more than one variable in a line using ',' you have to follow same patter for compiler understanding.

for example,

int a = 2,b ; //  warning C4101: 'b' : unreferenced local variable.

solution:1

int arr[] = {12, 34, 54, 2, 3}, i(0); // you may write i = 0;

If you initialize value than initialize for all variables of that line.

solution:2

int arr[] = {12, 34, 54, 2, 3};
int i;

And i recommend to you follow this rule for all datatype.

Upvotes: 0

Kun Han
Kun Han

Reputation: 1

It's the same as:

int arr[] = {12, 34, 54, 2, 3};
int i;

Upvotes: 0

I. Ahmed
I. Ahmed

Reputation: 2534

The i part is a integer variable. Its same as declareing as separate follows where arr is initialised with 5 items and i is not initialised:

int arr[] = {12, 34, 54, 2, 3};
int i;

For more illustration if you compile the following code:

#include <iostream>

using namespace std;

int main()
{
    int arr[] = {12, 34, 54, 2, 3}, i = 5;
    cout<<"Print Arr[4] = "<<arr[4]<<"\nPrint i = "<<i;

    return 0;
}

Then it will print:

Print Arr[4] = 3                                                                                                                      
Print i = 5 

From the above code you can understand that the arr and i are separate variable.

Upvotes: 0

user5833601
user5833601

Reputation:

Honestly, it just looks like they are declaring variables.

I.E

int i, j;

is basically the same as

int i;

int j;

It seems to be mostly personal choice for either method.

Hope this helped!

Upvotes: 0

Barmar
Barmar

Reputation: 780655

A declaration statement can declare multiple variables with the same type, separated by comma. So this is just declaring two variables, arr, and i. It's equivalent to:

int arr[] = {12, 34, 54, 2, 3};
int i;

Upvotes: 1

Pablo
Pablo

Reputation: 13570

This is the same as doing

int arr[] = {12, 34, 54, 2, 3};
int i;

You can declare and initialize more than one variable in a line, using ,. In this case arr is initialized with 12, 34, 54, 2, 3 and i is just declared, but not initialized.

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 992707

This is just initialization syntax. It's equivalent in structure to:

int a = 0, i;

except that arr is the first variable declared, and it's given an initial value. i is the other variable declared, and it is not given an initial value.

Upvotes: 3

Related Questions