user5494873
user5494873

Reputation:

Initialize a constant size array with previously defined variables

I have tried creating a simple array of size 12, to hold all the months in the year. The months are integers that hold the number of days for that month. But I am getting some very odd behavior (shown below).

#include <iostream>
using namespace std;

int main()
{
  int sep, apr, jun, nov = 30;
  int jan, mar, may, jul, aug, oct, dec = 31;
  int feb = 28;
  int year = 1900;
  if(year%4 == 0 && year%100 != 0)
    feb = 29;
  if(year%100 == 0 && year%400 == 0)
    feb = 29;

  int months[12] = {jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec};

  for(int i = 0; i < 12; i++)
    cout << months[i] << endl;

  return 0;
}

This is what it outputs:

4196853
28
0
0
383843232
-1082535160
54
4196784
4195939
0
30
31

I have no idea why its doing this, please let me know what I am doing wrong. I honestly might just give up on array and stick with vectors...

Thank you.

Upvotes: 0

Views: 53

Answers (2)

Balu
Balu

Reputation: 2447

int sep, apr, jun, nov = 30; should be int sep = 30 , apr=30, jun = 30, nov = 30;

int jan, mar, may, jul, aug, oct, dec = 31; should be int jan=31, mar=31, may=31, jul=31, aug=31, oct=31, dec = 31;

the array is initialized with uninitialized variables and printing junk values they have.

Upvotes: 1

Jarod42
Jarod42

Reputation: 217085

in

int sep, apr, jun, nov = 30;

only nov is initialized. It should be

int sep = 30, apr = 30, jun = 30, nov = 30;

Upvotes: 3

Related Questions