From the January 2016 Issue of Prestwood eMag
 
C++ Language Basics:
C++ Custom Routines
 
Posted 11/16/2008 on 11/16/2008 and updated 12/25/2008
C++ Code Snippet:

KB101632

Languages Focus: Custom Routines

For non-OOP languages, a custom routine is a function, procedure, or subroutine and for pure OOP languages, a custom routine is a class method. Hybrid languages (both non-OOP and OOP) combine both.

C++ Custom Routines

C++ is a hybrid language and as such offers global functions and class methods. A function must come before it's usage or you can prototype the function.

Syntax Example:
void sayHello(string pName) {
cout << "Hello " + pName + "\n";
};
 
int add(int p1, int p2) {
int result;
 
  result = p1 + p2;
return result;
};

Prototyping

The following is the complete C++ source code for a simple console application that demonstrates prototyping.

You either have to define your custom routines above main() so that they can be used within main() or prototype them. C++ allows you to prototype custom routines so that you can put their implementation below main.

#include "stdafx.h"
#include <iostream>
#include <string>
 
using namespace std;
//
//Prototypes
//
void sayHello(string pName);
int add(int p1, int p2);
 
//
//Main.
//
void main()
{
sayHello("Mike");
cout << "2+2=" << add(2,2) << "\n";
}
 
//
//Implementation section.
//
void sayHello(string pName) {
cout << "Hello " + pName + "\n";
}
 
int add(int p1, int p2) {
int result;
  result = p1 + p2;
return result;
}
Code Contributed By Mike Prestwood:

Mike Prestwood is a drummer, an author, and creator of the PrestwoodBoards online community. He is the President & CEO of Prestwood IT Solutions. Prestwood IT provides Coding, Website, and Computer Tech services. Mike has authored 6 computer books and over 1,200 articles. As a drummer, he maintains play-drums.com and has authored 3 drum books. If you have a project you wish to discuss with Mike, you can send him a private message through his PrestwoodBoards home page or call him 9AM to 4PM PST at 916-726-5675 x205.

Visit Profile
www.prestwood.com For service: 916-726-5675
or support@prestwood.com
Copyright (C) Prestwood IT Solutions.
All Rights Reserved.
Printed 9/27/2020