Did you know..? C and C++ Tips 5
In this episode of Did you know…? we take another look at some common coding mistakes.
- Undeclared Functions
- Extra Semicolons
Undeclared Functions
Many beginning programmers make the mistake of not declaring function.
Take the following example:
int main()
{
my_function();
}
void my_function()
{
//some code
}
A compiler walks the program from the top to the bottom, so in this case the compiler doesn’t know of my_function() until it is past main(). The result is that the first time the compiler sees my_function() it says that it doesn’t know my_function(). There are two ways to fix this. The first one is placing main() at the bottom of the program. The other is to declare the function upfront, like in the example below:
void my_function();
int main()
{
my_function();
}
void my_function()
{
//some code
}
Extra Semicolons
Another common mistake beginning programmers make is putting an extra semicolon after an “if statement”,
loop or function definition. The result is that the program will not work correctly.
An example of a program that will not work correctly, because of a misplaced semicolon the program will display 10, instead of 0 to 9:
#include<iostream>
using namespace std;
int main(void)
{
int a;
for(a=0; a < 10; a++); //note the wrong semicolon
{
cout << a;
}
}
If you remove the semicolon the program should work correctly.