Basic question; passing data type to function

Hello, I created a function 'addOneDay' using a special data type "Date".
if I call such function, what would be the correct way to pass the data type in this case? It is not accepting what I did below;

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

#include <iostream>

//Create Date struct so I can manipulate year, month and day later
struct Date {
    int year;
    int month;
    int day;
    
};

//This function will increment a given day by 1
Date addOneDay(const Date & date ) {
    Date newDate = date;
    newDate.day += 1; //Increment day by 1
    std::cout << newDate.day << std::endl; //display it
}

int main()
{ 
    //Data type I need to pass is "Date".
    //Now I want to pass for example day 20 and increment it by 1.
    Date mydate;
    mydate.day = 20;
    addOneDay(mydate.day); //<== data type ERROR HERE 
    
    return 0;

    
}
Last edited on
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
#include <iostream>

struct Date {
    int year;
    int month;
    int day;    
};

//This function will increment a given day by 1
Date addOneDay(const Date & date ) {
    Date newDate;
    newDate.day  = date.day + 1; //Increment day by 1
    return newDate;
}

int main()
{
    Date mydate;
    mydate.day = 20;
    
    Date new_date = addOneDay(mydate);
    std::cout << new_date.day << '\n';
    
    return 0;
}
Last edited on
There is of course the other alternative where the same date is being incremented:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

struct Date {
    int year;
    int month;
    int day;    
};

//This function will increment a given day by 1
void addOneDay( Date & date ) {
    date.day++; //Increment day by 1
}

int main()
{
    Date mydate;
    mydate.day = 20;

    addOneDay(mydate);
    std::cout << mydate.day << '\n';
    
    return 0;
}
Or even this which is possibly better:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

struct Date {
    int year;
    int month;
    int day;  
    
    void addOneDay() 
    {
        day++; //Increment day by 1
    }
};

int main()
{
    Date mydate;
    mydate.day = 20;

    mydate.addOneDay();
    std::cout << mydate.day << '\n';
    
    return 0;
}
And getting closer to a full-blown class:

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
#include <iostream>

struct Date {
    int year;
    int month;
    int day; 
    
    Date(int yy, int mm, int dd)
    {
        year = yy;
        month = mm;
        day = dd;
    };
    
    void addOneDay() 
    {
        day++; //Increment day by 1
    }
};

int main()
{
    Date mydate(2020,2,20);
    mydate.day = 20;

    mydate.addOneDay();
    std::cout << mydate.year << ' ' << mydate.month << ' '  << mydate.day << '\n';
    
    return 0;
}
Topic archived. No new replies allowed.