How is max3() using global variables in a bad way?

How is max3() using global variables in a bad way?

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
#include <iostream>
#include <cmath>
using namespace std;
int maximum;


void set_max(int a)
/* PURPOSE:   Updates maximum if parameter is larger
   RECEIVES:  a - the value to compare against maximum
   REMARKS:   Uses global int maximum  
*/
{  if (maximum < a)
   {   maximum = a;
   }
}
void max3(int &i, int& j, int& k)
{  maximum = i;
   set_max(j);
   set_max(k);
   return maximum;
}

int main()
{   cout << "Please enter the first integer: ";
    cin >> i;
    cout << "Please enter the second integer: ";
    cin >> j;
    cout << "Please enter the third integer: ";
    cin >> k;
    maximum = max3(i, j, k);

    cout << "The maximum is " << maximum << "\n"
    return 0;
}
First of all I do not see where i, j, and k are declared in your program
As for the program then it can be written simpler without using any global variable.

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>

using namespace std;


int max3( int i, int j, int k )
{
    int max = i;

    if ( max < j ) max = j;   

    if ( max < k ) max = k;
   
    return  ( max );
}

int main()
{
    int i, j, k;
   
    cout << "Please enter the first integer: ";
    cin >> i;
    cout << "Please enter the second integer: ";
    cin >> j;
    cout << "Please enter the third integer: ";
    cin >> k;

    cout << "The maximum is " << max3( i, j, k ) << "\n"

    return 0;
}
Topic archived. No new replies allowed.