why does it gives me a random number instead of syntax error?

I was programming a program to calculate the area of a rectangle. I wrongly typed :

cin >> width , length ;

instead of the correct one :

cin >> width >> length ;

What happens is that , when I enter the first input , it gives me a random number ( positive or negative )

Why does this happen instead of giving me a syntax error ?
any explanation?

Note : I'm absolutely cpp beginner . I have taken my first lecture today.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
int width , length;

cout << "Enter width of the rectangle first , then the length \n";
cin >> width , length ;

cout << "the area of the rectangle is "<< width * length << "\n";

return 0;
}
because of your mistake length is never given a value so length contains garbage. So the results of width * length is undefined.
Last edited on
The comma operator first evaluates the first operand (cin >> width) and then it evaluates and returns the result of the second operand (length).

Because length is left uninitialized its value is undefined.
Last edited on
Ok , length is undefined. Does this means it returns random number ? why not tell me that this thing is not defined ?
Hi Im not sure if this works but try doing this:
 
cin>>width>>length;
Does this means it returns random number ?

It means you can't be sure what value it will have, but it will probably not be very random so it's not a good way of generate random numbers. Instead use std::rand() or one of the random engines in C++11.

why not tell me that this thing is not defined ?

You mean why doesn't the compiler tell you? It will if you turn on more warnings. GCC (or MinGW on Windows) will warn you if you pass the -Wall compiler flag.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// g++ -Wall test.cpp
#include <iostream>
using namespace std;

int main()
{
	int width , length;

	cout << "Enter width of the rectangle first , then the length \n";
	
	// warning: right-hand operand of comma has no effect
	cin >> width , length ; 

	// warning: ‘length’ is used uninitialized in this function
	cout << "the area of the rectangle is "<< width * length << "\n";

	return 0;
}
Last edited on
Yes , I mean the compiler. How to turn on more warnings ?

I use Code Blocks as a compiler . How to turn more warnings so that it gives me an error in this case ?
Topic archived. No new replies allowed.