C++ Programming: Functions (Lesson 5)

Let’s have a look at this simple code to understand syntax of functions in C++. #include using namespace std; int add(int x, int y) { return x+y; } int main() { int result = add(1,2); cout << "The result is " << result << "n"; } Here, we created a function called add so we can call it in our main function. In order to call a function in main, it has to be declared or defined before the main function. In the programming above, we defined the function first. We could also have declared the prototype of the function first and then define the function wherever we want. #include using namespace std; int add(int x, int y); int main() { int result = add(1,2); cout << "The result is " << result << "n"; } int add(int x, int y) { return x+y; }
This material is from the textbook Jumping into C++ by Alex Allain. I strongly recommend this book if you are new to programming and want to learn more than what I described here.
Click for Lesson 4
This entry was posted in Programming and tagged , . Bookmark the permalink.