Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    cpp
  » Intro to Functions
      by mochman
 Page 1 of 1 
   

(Login to remove green text ads)
Here is an introduction to creating and using functions in C++.

Code:
#include<iostream.h> #include<conio.h> //Function Prototype int ourFunction( int ); int main(void) { int userInput = 0; // get a value from the user cout << "Please enter an integer :"; cin >> userInput; // just to see the difference we will output the old value cout << "The old value is " << userInput << endl; // the function is being called here // you can also make a new variable and have it = ourFunction( userInput ) cout << "The new value is " << ourFunction( userInput ) << endl; //Wait for a user to press any key to continue getch(); return 0; } // Now the function is created // the function will return an int // and take in an int called valueIn int ourFunction( int valueIn ) { cout << "being changed to "; valueIn = valueIn * 2; return valueIn; }

To start off, we will first need to create a prototype for the function we are making, this is usualy placed at the top of the file right around the #includes. The prototpye shows what values are passed in and if any values are returned from it.

int ourFunction( int )

(int #1) If the function is going to return a value, the type is here, if the function isn't going to return a value, "void" will be here instead.

(int #2) Values being passed in, multiple values can be separated by commas.


int ourFunction( int valueIn ) {

The function is then placed at the end of the file. The syntax for that is the same as the prototype with a variable names for the passed in values. This is then followed by a "{" to start the function.
The function is then coded, in our case our function tells the user that we are modifying the data, then we double the inputted value. After that we return it, so that our main function can use it.
Don't forget to close the function off with a "}" or the compiler will yell at you.




 
 Page 1 of 1 
   

Rate This Article
1 2 3 4 5 6 7 8 9 10





Copyright © 2000-2006, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting
Open Circle