Negative index in array

I'm working on designing a class Day of the Year that takes an integer representing a day of the year and translates it to a string consisting of the month followed by day of the month

Here is my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
#include<cstdlib>
using namespace std;

class DayOfYear
{
	private:
		int day;
		static int Monthday[];
		static string Month[];
		
	public:
		DayOfYear(int d)
		{ 
			if(d <= 0){
				cout << "Must be a positive interger!\n";
				exit(EXIT_FAILURE);
			}
			
			day = d; 
		}
			
		void print();
};

/*set day for each month*/
int DayOfYear::Monthday[12] = {31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
/*month of the year*/
string DayOfYear::Month[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September",
								"October", "November", "December"};

void DayOfYear::print()
{
	int month = 0;
	
	while(Monthday[month] < day)
		month++;

	cout << "Day " << day << " would be " << Month[month] << " " << day - Monthday[month-1] << endl; 
		
}	

int main()
{
	int d;
	
	cout << "Enter the day in the year: ";
	cin >> d;
	DayOfYear Day(d);
	
	Day.print();
	return 0;
}

this code works perfectly but what I don't get it is that if I enter a day less than 31 ( i.e a day in Jan), then month - 1 would be -1 and the array would accept an negative index. I tested by printing Monthday[-1] and I got 0. I don't understand why
Last edited on
Accessing the elements outside the bounds of the array causes undefined behavior. Literally anything can happen. In your case, Monthday[-1] simply accessed the int that was one position below Monthday[0], which happened to be equal to zero.

I would change DayOfYear::Monthday like so:
 
int DayOfYear::Monthday[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
and get rid of the -1 on line 39.

Don't forget about leap years! I was born on a February 29th and it annoys me to no end when someone makes a birthday entry form that doesn't account for that date.
I approach this problem in a simple case first i.e I assume a year has 365 days

Anw, thank you so much, it helps me a lot
Topic archived. No new replies allowed.