Basic Class question

This piece of code was used in one of my teachers examples, but there was no comment to explain what it does.

1
2
3
4
5
6
7
8
9
10
11
void Date::displayDateFormat1() const
{
     // Display date as mm/dd/yy
     
     cout << "\n" << (month < 10 ? "0" : "") 
          << month << "/" 
          << (day < 10 ? "0" : "")
          << day << "/" 
          << (year < 10 ? "0" : "")
          << year << endl;     
}


I don't know what the underlined code is doing. In general the month < 10, "?" and the ":" What is it for?

Thanks for your help.
They are just different forms of if-statements. The first one is (and the others follow with the same reasoning) if month is less than 10, cout "0". Otherwise cout "".
Ok I follow...so if I chose March which is 3...it would display 03 instead of just 3. I just had never seen this before.

Thanks
Yes all this does is check if the month is less than 10. If so, it adds a zero. It is equivalent to this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if (month < 10) {
    cout << "0";
} else  {
    cout << "";
}
cout << month << "/";
if (day < 10) {
    cout << "0";
} else {
    cout << "";
}
cout << day << "/";
if (year < 10) {
    cout << "0";
} else {
   cout << "";
}
cout << year << endl;


Obviously what he did is much more compact and readable once you understand it.
Last edited on
Thanks for the visual.
Topic archived. No new replies allowed.