Hi can someone help in in understanding the following code esp the "?".I cant understand how the output 9:10:5 as obtained.
Thank You.
The code is as followed:

#include <iostream>
using namespace std;

int main()

short  hour =9, minute =10, second =5;
cout << (hour <10 ? "0":"" )<<hour<<":"
     << (minute <10 ? "0":"" )<<minute<<":"
	 << (second <10 ? "0":"" )<<second<<endl;


return 0;

Edited by Nick Evan: Added CODE tags

5 Years
Discussion Span
Last Post by Narue

It's simple. Just break them into segments.
hour < 10 ? "0" : " "
The hour <10 part tells that if value of hour is less than 10 then 0 will be displayed, if hour is not less than 10 then it displays nothing.
If the condition is satisfied then the expression following ? is done if the condition is not satisfied then the expression after : is done.

Use code tags

Edited by Arbus: n/a


It is a conditional statement of the form [(boolean expression evaluation) ? (execution in case of true) : (execution in case of false)].Much like an if else statement.In this particular case if (hour<10) will evaluate to true a "0" will be inserted first in the cout stream and a "" otherwise.


I know you asked about the conditional operator, but the following is a more conventional way of adding leading zeros to a fixed field width:

#include <iomanip>
#include <iostream>

using namespace std;

int main()
    short hour = 9;
    short minute = 10;
    short second = 5;
    char last_fill = cout.fill('0');
    cout << setw(2) << hour << ":"
         << setw(2) << minute << ":"
         << setw(2) << second << endl;

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.