-1

I am trying to learn C++ and have an issue with a small conversion program about time formats.

    #include <iostream>
    using namespace std;

    void conversion(int hours, int minutes) {
       if (hours > 12) {
           hours -= 12;
           minutes = minutes;
       }
       else
           hours = hours;
           minutes = minutes;

       cout << hours << ":" << minutes << endl;
       }

    void output(int hours, int minutes) {
        cout << hours << ":" << minutes;
    }

    int main() {
        int hours, minutes;
        cout << "Enter the hours: ";
        cin >> hours;
        cout << "Enter minutes: ";
        cin >> minutes;
        conversion(hours, minutes);
        output(hours, minutes);

    }

In the main function, the output call is not receiving the updated values for hours and minutes.

nobody
  • 19,814
  • 17
  • 56
  • 77
Alex Haugen
  • 9
  • 1
  • 2
  • In c++, you can get the the return from a function, or pass a parameter to the function (pass by reference or pointer) to be changed inside. In your code, `hours` and `minutes` inside the function conversion are a copy of the variables received.. so they are not being changed outside. Check this [answer](http://stackoverflow.com/questions/19827119/c-argument-passing-passed-by-reference) to see an example of function using `passing by reference`. – wendelbsilva Dec 11 '15 at 21:23
  • @wendelbsilva Alright, thank you. I think I got it. – Alex Haugen Dec 11 '15 at 21:26
  • Consider not passing in the minutes. They appear unaffected and don't need to be a parameter. – Kibitz503 Dec 11 '15 at 22:45

1 Answers1

0

This has nothing to do with time formats. A much smaller program that shows the same problem is:

#include <iostream>
using namespace std;

void f(int i) {
   i = 20;
}

int main() {
    int i = 10;
    f(i);
    cout << "i is still " << i << endl;
}

The problem is that int i in the parameter list means "pass by value". The function gets a copy of the value. Any changes you make to that copy are thrown away when the function exits. Either pass by reference (void f(int& i)) or by pointer (void f(int *pi)). Look up reference and pointers in your text book.

There are also a number of issues in your function:

void conversion(int hours, int minutes) {
   if (hours > 12) {
       hours -= 12;
       minutes = minutes;  // This line does nothing.
   }
   else
       hours = hours;      // This line does nothing.
       minutes = minutes;  // This line will get executed even if hours was originally
                           // >12.  (Only the hours=hours line is covered by the else).  

   cout << hours << ":" << minutes << endl;
   }

You probably wanted:

void conversion(int& hours, int& minutes) {
   if (hours > 12) {
       hours -= 12;
   }
   cout << hours << ":" << minutes << endl;
}