MNK
MNK

Reputation: 664

C++ different outputs on different runs

I am running a very simple C++ code to find the highest of 5 user-entered integers. The code is sometimes working (usually after compiling with g++) and aometime not.

#include <iostream>
using namespace std;

int main()
{
    int arr[5], max;
    cout<<"Enter the 5 scores: ";
    cin>>arr[0];

    for (int i=1; i<5; i++)
        {
        cin>>arr[i];
        if (arr[i]>max)
            {
            max = arr[i];
            }
        }

    cout<<"Highest score is "<<max<<endl;
    return 0;
}

Following are some of the command-line laterons.

(base) adam@legion:~/C++$ g++ -pedantic -std=c++11 -Wall max_input.cpp 
(base) adam@legion:~/C++$ ./a.out
Enter the 5 scores: 1 2 3 4 5
Highest score is 5
(base) adam@legion:~/C++$ ./a.out
Enter the 5 scores: 1 2 3 4 5
Highest score is 513655632
(base) adam@legion:~/C++$ 

I do not know what is wrong.

Upvotes: 1

Views: 122

Answers (1)

paddy
paddy

Reputation: 63471

You have not initialized max, so your program has undefined behavior.

It's a good idea to enable all warnings in your compiler. With g++, that would be -Wall. This will help you detect several kinds of basic mistakes that can lead to undefined behavior.

For this program, the compiler will easily be able to see that max is being used in a comparison before ever being assigned a value, and it should issue a warning.

The simplest fix is to assume the first value in the array is the maximum:

cin >> arr[0];
max = arr[0];

Alternatively, initialize max to the minimum possible value. However, this wouldn't work directly in your current program, because you're reading the first value outside the loop and not testing it. So your program would move the reading of all values into the loop.

int max = std::numeric_limits<int>::min();
for (int i = 0; i < 5; i++)
{
    cin >> arr[i];
    if (arr[i] > max)
    {
        max = arr[i];
    }
}

Upvotes: 5

Related Questions