Page 1 of 1

Functions in C and C++, Part I: The Basics Rate Topic: ***** 7 Votes

#1 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6091
  • View blog
  • Posts: 23,605
  • Joined: 23-August 08

Posted 21 December 2010 - 05:55 AM

*
POPULAR

Many people come to Dream.In.Code with a great deal of confusion over
functions. I'm going to make an attempt here at DIC to clear up some of
this confusion in this short series of tutorials.

Functions allow you to break your code up into individual logical
constructs which make your code easier to read, maintain, and debug.
A function ideally will perform a single action.

Function Declaration

A function must be declared before it can be called within your
code. This is done by the use of a prototype, which must appear in your
code before its use (because the compiler starts from the top of the
code file and proceeds through the file). The prototype should appear
outside of all other functions.

A function is declared as follows:

return-type function-name (arguments-to-function)

The return-type is the data type which this function will be returning
to the caller. If the function will not be returning anything to the
caller, for example if it's a function that simply prints some data,
then the return-type will be void, meaning it returns nothing.

The function-name must be a unique name and is
the name you will be using to run the function. For maximum readability
you should name your functions for the action it performs.

The arguments to the function are the data on which the function will
operate. These arguments are in the format of data-type
variable-name
. Note that C and C++ pass all arguments by value, which
is important and will be explained later in this tutorial.

Here is a very simple example function declaration which takes no
arguments and returns nothing to the caller:
void printUsage(void);


Here is a simple function declaration which takes two integer arguments
and returns an int to the caller:
int multiplyIntegers(int x, int y);


Function Definition

Once you've declared to your compiler that you are going to create a
function, before you use it you must define the function. You define the
function by creating in code a function which exactly matches
the prototype you provided previously. If the function definition does
not match exactly, you will receive linker errors (undefined
external symbol, for example) during the linking phase of the build
process.

Let's define the second example above, multiplyIntegers():

int multiplyIntegers(int x, int y)
{
     int result;

     result = x * y;

     return result;
}


Pretty simple function, but let's dive a little deeper into exactly
what's happening here.

int multiplyIntegers(int x, int y)


This is the function signature, matching the prototype previously
declared. The values passed from the caller are copied into new
variables named x and y which exist only for the
duration of the function. C and C++, as noted before, uses
pass-by-value semantics. This means that when the function
is called, the variables being passed are copied prior to being
passed to the function. This means that anything you do to these variables
within the function does not affect the variable in the calling routine.
More on this forthcoming in the next tutorial.

{


Starts the scope of the function. Note that the use of brackets --
{ and } -- introduces a new scope. When you create a
scope with {, any variables you declare and use exist only for
the duration of the scope, i.e. when the matching end bracket } is found.

int result = 0;


This line declares a new integer variable, result which is
local to the multiplyIntegers() function. This will, as you
might imagine, hold the result of the multiplication.

result = x * y;


Multiplies the variables x and y and assigns the
variable to the local variable result.

return result;


Passes the value of result back to the caller of the
function. Remember when I said earlier that all variables created within
a scope are local to the scope in which they were created? Well, because
we want the caller to receive the value we calculated in the function we
must get that value back to the caller. Using return
accomplishes that by making a copy of the local variable and providing
that copy to the caller.

}


Ends the scope of the function.

Calling the Function

Now that we've declared the function, and defined the function, we can
call it from our main code. You accomplish this with the following
general syntax:

function-name(arguments);


So in order to call our function from our main routine, we would write:

multiplyIntegers(a, b);


This will call our function with the variables a and
b, which would be declared and initialized within the main
function. Note that the datatype of the arguments is NOT part of the
function call itself!

There's a problem though, isn't there? Where does the result end up?
Well, the function itself returns the result, so we must assign that
value to a variable in the calling routine, like so:

int multiplicationResult = multiplyIntegers(a, b);


This will take the result variable from the function and assign
it to the local variable multiplicationResult. You may then use
that variable however you see fit.

Here's how it all fits together:
#include <stdio.h>

/* Our function prototype */
int multiplyIntegers(int x, int y);

/* Our main routine */
int main(void)
{
    /* Our multiplication operands */
    int a = 3;
    int b = 4;

    /* Call our function */
    int multiplicationResult = multiplyIntegers(a, b);

    /* Print the result */
    printf("%d x %d = %d\n", a, b, multiplicationResult);

    /* main is a function too, and it returns an int to the caller,
        which in this case is the operating system.
        Returning 0 from main indicates success */
    return 0;
}

/* Our function declaration */
int multiplyIntegers(int x, int y)
{
     int result;

     result = x * y;

     return result;
}


The next tutorial will cover more advanced topics, such as getting around
pass-by-value to alter the variables passed and return multiple values from
the function, arrays and pointers.

Part II: Functions in C and C++: Pass-By-Value vs. Pass-By-Pointer and Arrays

Is This A Good Question/Topic? 38
  • +

Replies To: Functions in C and C++, Part I: The Basics

#2 MATTtheSEAHAWK  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 137
  • View blog
  • Posts: 782
  • Joined: 11-September 10

Posted 21 December 2010 - 07:56 AM

Thanks so much for this! I was wondering if you had to do this everytime. Thanks man. :) *green button pressed.
Was This Post Helpful? 1
  • +
  • -

#3 Ronald91  Icon User is offline

  • New D.I.C Head

Reputation: 11
  • View blog
  • Posts: 31
  • Joined: 26-April 09

Posted 21 December 2010 - 01:37 PM

Once one has a superb understanding of functions even the hardest C/C++ programs will be easy to create and debug. I recently had to emulate a washing machine for my final embedded systems class and the code came up to 406 lines. For simplicity I will just post my function prototypes and my main.

void MSDelay(unsigned int);
void init_PortH_INT(void);
void init_switches(void);
void spritz(void);
void states(void);
void display(void);
void init_ATD(void);
void init_PLL(void);
void level_set(void);
void turn_180(void);
void turn_360(void);
void turn_3601(void);
void init_lights(void);
void init_PWM(void);
void determine_settings();

void main()
{  
  while(1){
    init_PLL( );
    init_PWM();
    openLCD();
    init_ATD();	                         // ATD unit 0 initializations
    
    init_lights();
    
    init_PortH_INT( );
    EnableInterrupts;
    init_switches();
    i=0;
    init_washer=PTH;
   
        
        
    while(1){
        
        init_washer=PTH;
        if(init_washer==0x03)        
        states();
        
        if(init_washer!=0x03){
                
        openLCD();
        putsLCD("Close Lid+Start"); 
        MSDelay(4000);
        
        
        } 
    }
   
     }
}


Was This Post Helpful? 2
  • +
  • -

#4 Aphex19  Icon User is offline

  • Born again Pastafarian.
  • member icon

Reputation: 615
  • View blog
  • Posts: 1,873
  • Joined: 02-August 09

Posted 24 December 2010 - 12:31 AM

Ronald91's code.

:crazy:
void main()

Was This Post Helpful? 0
  • +
  • -

#5 Ronald91  Icon User is offline

  • New D.I.C Head

Reputation: 11
  • View blog
  • Posts: 31
  • Joined: 26-April 09

Posted 24 December 2010 - 06:33 AM

I know, always use int main with return 0. However, since the code ran on the I-O board without an operating system I think it should not be a serious issue.
Was This Post Helpful? 0
  • +
  • -

#6 marinus  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 135
  • View blog
  • Posts: 575
  • Joined: 14-April 10

Posted 03 April 2011 - 11:15 PM

You could hide your C++ in a header file and call the prototypes where you need them.
To clean your code from prototype functions on top of the code.

for example

prototypes.h

int Calculus (int , int );


then in main.cpp
#include prototypes.h

int Calculus (int a ,int B)/>{
return a - b;

}



Or you could just make a class :)

This post has been edited by marinus: 03 April 2011 - 11:21 PM

Was This Post Helpful? 2
  • +
  • -

#7 fiston  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 28
  • Joined: 10-January 12

Posted 19 January 2012 - 10:03 AM

quite helpful!
Was This Post Helpful? 0
  • +
  • -

#8 CraftTNT  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 24-July 12

Posted 25 July 2012 - 02:41 PM

Thanks for the help! I'm new to DIC and learning C++ and i have been learning C++ and this really makes it sound like its not that complex! Thanks again!
Was This Post Helpful? 0
  • +
  • -

#9 Roonil Wazlib  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 30
  • Joined: 03-August 12

Posted 04 August 2012 - 03:12 AM

Thanks for the help, mate. Nice work.
Was This Post Helpful? 0
  • +
  • -

#10 limpylegs  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 02-January 13

Posted 03 January 2013 - 12:07 AM

Hey guys! I'm still new to this I was wondering if somebody could tell me why we put the function prototype at the top,then put the function declaration down at the bottom?I've been watching a few video tutorials and e-books that just simply put the function declaration at the top of the code.Is that the wrong thing to do?

I'm still relatively new to C++ and was wondering why you put a function prototype at the top of the code and a function declaration at the bottom as well?I've been looking at other tutorials that have showed me to simply put the function declaration at the top of the code and it has ran just fine,is this considered a 'bad' thing to do?
Was This Post Helpful? 0
  • +
  • -

#11 raghav.naganathan  Icon User is offline

  • Perfectly Squared ;)
  • member icon

Reputation: 408
  • View blog
  • Posts: 1,440
  • Joined: 14-September 12

Posted 03 January 2013 - 12:08 AM

View Postlimpylegs, on 03 January 2013 - 12:34 PM, said:

Hey guys! I'm still new to this I was wondering if somebody could tell me why we put the function prototype at the top,then put the function declaration down at the bottom?I've been watching a few video tutorials and e-books that just simply put the function declaration at the top of the code.Is that the wrong thing to do?


Well, the reason for it is the prototype informs the compiler that there is a function by a particular name which will be encountered in the program.

It can also be avoided if you directly start with defining the functions before your main() function.

As far as I know, it is not a wrong thing at all.

regards,
Raghav
Was This Post Helpful? 0
  • +
  • -

#12 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6091
  • View blog
  • Posts: 23,605
  • Joined: 23-August 08

Posted 03 January 2013 - 04:55 AM

The answer to the question is right in the tutorial:

Quote

A function must be declared before it can be called within your
code. This is done by the use of a prototype, which must appear in your
code before its use (because the compiler starts from the top of the
code file and proceeds through the file
).


When the compiler reaches a function call, it needs to know about it, or it will treat it as an error.
Was This Post Helpful? 0
  • +
  • -

#13 skeeteR  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 07-August 13

Posted 08 August 2013 - 03:48 PM

thank you very much jack. this is very very helpful. :)
Was This Post Helpful? 0
  • +
  • -

#14 cody.read  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 21-October 14

Posted 30 October 2014 - 12:37 PM

Very detailed and explained. Thank you for this!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1