C ++ programming error
I recently started learning C ++ but I ran into a problem. The program below does not give me the desired result, since I only see "Hello" in the result, but not what is written in the void function. Please tell me why this happens along with the solution.
I am using Xcode 6.3.1 and I chose C ++ language.
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
void ABC ();
return 0;
}
+3
source to share
6 answers
you need to call your method and not declare it inside the main
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}
EDIT 1: Since you started learning C ++, I recommend the following guidelines to make sure your code is cleaner. Please note that these are not rules by any means, but more best practices and coding style.
- Use meaningful names for your variables, methods, functions, classes ... So instead of ABC () name it something that if you (or someone else reads it) would now be what it should do.
- When calling methods and functions, try to declare them with an appropriate return value. Void, by definition, does not return any; it just processes the code inside it. so your methods / functions should return the appropriate values โโof what it suggested.
Here's version 2 of your code with examples of 3 different methods and calls:
#include <iostream>
using namespace std;
int sum;
string MethodReturningString()
{
return "Hey there i am the result of a method call !";
}
int MethodReturningInt()
{
return 5;
}
void CalculateSum(int x,int y)
{
sum=x+y;
}
int main()
{
cout << MethodReturningString() << endl;
cout << MethodReturningInt() << endl;
cout << "Calculating sum:" ;
CalculateSum(5,4);
cout << sum << endl;
return 0;
}
Happy coding
+4
source to share