1.Undeclared Variables
int main()
{
cin>>x;
cout<<x;
}
Why do I get an error?
Your compiler doesn't know what x means. You need to declare
it as a variable.
int main()
{
int x;
cin>>x;
cout<<x;
}
2.Using a single equal sign to check equality
char x='Y';
while(x='Y')
{
//...
cout<<"Continue? (Y/N)";
cin>>x;
}
"Why doesn't my loop ever end?"
If you use a single equal sign to
check equality, your program will instead assign the value on the right side of
the expression to the variable on the left hand side, and the result of this
statement is the value assigned. In this case, the value is 'Y', which is
treated as true. Therefore, the loop will never end. Use == to check for
equality; furthermore, to avoid accidental assignment, put variables on the
right hand side of the expression and you'll get a compiler error if you
accidentally use a single equal sign as you can't assign a value to something
that isn't a variable.
char x='Y';
while('Y'==x)
{
//...
cout<<"Continue? (Y/N)";
cin>>x;
}
3.Undeclared Functions
int main()
{
menu();
}
void menu()
{
//...
}
"Why do I get an error about menu being unknown?"
The compiler doesn't know what
menu() stands for until you've told it, and if you wait until after using it to
tell it that there's a function named menu, it will get confused. Always
remember to put either a prototype for the function or the entire definition of
the function above the first time you use the function.
void menu();
int main()
{
menu();
}
void menu()
{
...
}
No comments:
Post a Comment