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>
usingnamespace 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;
}
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>
usingnamespace 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;
}