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.

44 CHAPTER 2. <strong>C++</strong> BASICS<br />

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

return std::floor( a / b ) ;<br />

}<br />

int main (){<br />

int x=5,y=2;<br />

float n=5.0,m=2.0;<br />

std::cout ≪ divide (x,y) ≪ std::endl;<br />

std::cout ≪ divide (n,m) ≪ std::endl;<br />

return 0;<br />

} % ≫ ≫ ≫ ≫<br />

In this case we have defined two functions with the same name, divide, but one of them accepts<br />

two parameters of type int and the other one accepts them of type float. In the first call to<br />

divide the two arguments passed are of type int, there<strong>for</strong>e, the function with the first prototype<br />

is called. This function returns the result of dividing one parameter by the other. The second<br />

call passes two arguments of type float, so the function with the second prototype is called.<br />

This one executes a similar division and rounds the result.<br />

2.6.5 Assertions<br />

The function assert is a special kind of function and has the following interface:<br />

void assert (int expression);<br />

If the argument expression evaluates to 0, this causes an assertion failure that terminates the<br />

program. A message is written to the standard error device and abort is called, terminating<br />

the program execution.<br />

The specifics of the message shown depend on the specific implementation in the compiler, but<br />

it shall include: the expression whose assertion failed, the name of the source file, and the line<br />

number where it happened. A usual expression <strong>for</strong>mat is:<br />

Assertion failed: expression, file filename, line linenumber<br />

This allows <strong>for</strong> a programmer to include many assert calls in a source code while debugging<br />

the program. The many assert calls may reduce the per<strong>for</strong>mance of the code and so it would<br />

be desirable to disable asserts <strong>for</strong> high-per<strong>for</strong>mance libraries. Asserts are disabled by including<br />

the following line<br />

#define NDEBUG<br />

at the beginning of his code, be<strong>for</strong>e the inclusion of cassert or by defining the variable in the<br />

compiler, e.g.<br />

g++ -DNDEBUG foo.cpp<br />

Example:<br />

#include <br />

#include <br />

int main ()<br />

{

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

Saved successfully!

Ooh no, something went wrong!