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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

In the first case, we have an int literal that is converted into float and in the second case, the<br />

literal is float from the beginning. For the sake of clarity, the float literal is preferable.<br />

Later in this book we will introduce function overloading, that is a function with different<br />

implementations <strong>for</strong> different argument types (or argument tuples). The compiler selects the<br />

function overload that fits best. Sometimes the best fit is not clear, <strong>for</strong> instance if function f<br />

accepts an unsigned or a pointer and we call:<br />

f(0);<br />

“0” is considered as int and can be implicitly converted into unsigned or any pointer type. None<br />

of the conversions is prioritized. As be<strong>for</strong>e we can address the issue by explicit conversion and<br />

by a literal of the desired type:<br />

f(unsigned(0));<br />

f(0u);<br />

Again, we prefer the second version because it is more direct (and shorter).<br />

The accuracy issue comes up when work with long double. On the author’s computer, the <strong>for</strong>mat<br />

can handle at least 19 digits. Let us define one third with 20 digits and print out 19 of it:<br />

long double third= 0.3333333333333333333;<br />

cout.precision(19);<br />

cout ≪ ”One third is ” ≪ third ≪ ”.\n”;<br />

The result is:<br />

One third is 0.3333333333333333148.<br />

The program behavior is more satisfying if we append an “l” to the number:<br />

long double third= 0.3333333333333333333l;<br />

yielding the print-out that we hoped <strong>for</strong>:<br />

One third is 0.3333333333333333333.<br />

The following table gives examples of literals and their type:<br />

Literal Type<br />

2 int<br />

2u unsigned<br />

2l long<br />

2ul unsigned long<br />

2.0 double<br />

2.0f float<br />

2.0l long double<br />

For more details, see <strong>for</strong> instance [Str97, § 4.4f,§ C.4]. There you also find a description how to<br />

define literals on an octal or hexadecimal basis.

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

Saved successfully!

Ooh no, something went wrong!