03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

2.6. FUNCTIONS 43<br />

foo takes one integer argument with default value 5 and one character argument with a default<br />

value of ‘A’. Now this function can be called by one of the three methods shown here:<br />

foo( 1, ’J’ );<br />

foo(24);<br />

foo();<br />

Which results in the following output:<br />

1 J<br />

24 A<br />

5 A<br />

Void functions<br />

When the result type of a function is void, we do not return a result. For example<br />

void foo( int i ) {<br />

std::cout ≪ ”My value is ” ≪ i ≪ std::endl ;<br />

}<br />

Constant arguments<br />

We can use const objects as arguments in functions to protect them from being changed. For<br />

example :<br />

bool bar( int const& x, int y ) {<br />

y = y+2;<br />

return y ==x ;<br />

}<br />

Since we do not want to modify x, we can add the keyword const. Note that const can be put<br />

be<strong>for</strong>e or behind the type, but it is recommended by the authors of this course to put it behind.<br />

2.6.4 Overloading<br />

In C ++, functions can share the same name as long as their parameter declarations are different.<br />

More precisely, the functions should differ in the number or the type of their parameters.<br />

The compiler can then use the number/type of the arguments to determine which version of<br />

the overloaded function should be used. Note that although overloaded functions may have<br />

different return types, a difference in return type alone is not sufficient to distinguish between<br />

two versions of a function.<br />

Consider the following example:<br />

#include <br />

#include <br />

int divide (int a, int b){<br />

return a / b ;<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!