is this code accurate?

I found the following code on the internet which indicates the maximum enter number. However I found the user didn't declare "max" in the first place, and the code happens to work indeed. Which confused me a lot!! Do I have to indicate max before it enters a while loop condition or there's no need?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;
int main()
{
	int x, max;
	
	cout<<"Enter integers (-1 to end): \n";
	cin>>x;
	
	while(x != -1)
	{
	if(x>max)
	max=x;
		
	cin>>x;
	}
	if(max == -1)
	cout<<"No integers entered";
	else
	cout<<"Maximum: "<<max<<endl;
	
	return 0;
}
Last edited on
Well you have to initialise max to something if that's what you mean.

This is what I see when I compile.
 
 In function 'int main()': 20:21: warning: 'max' may be used uninitialized in this function [-Wmaybe-uninitialized] 


Lets see:
Enter integers (-1 to end): 
-3
-4
-1
Maximum: 0

The program does clearly fail here. The correct answer would be -3.

The initial value of max could be anything, because it is not initialized with any known value. On that test run it happened to be 0. It could have been 132476579.

You want the max start with something that cannot be bigger than the input.
See http://www.cplusplus.com/reference/limits/numeric_limits/
int max = std::numeric_limits<int>::min();

Lets try a different input:
Enter integers (-1 to end): 
-1
Maximum: 0

An another failure. Let me update the code with proper initialization:
Enter integers (-1 to end): 
-1
Maximum: -2147483648



Okay, the program has two issues:
1. It relies has undefined behaviour (uninitialized max)
2. The logic of "no integers entered"


No. The code does not "work". It might look like giving expected output for some input, during some phases of the moon, but that is far from "working".
Last edited on
Topic archived. No new replies allowed.