C++ for a thirteen year old

Pages: 12345
Briefly, integral types are types that hold whole numbers.

The bool type holds one of the two truth values true and false.

An unsigned integral type holds 'natural' numbers that we use for counting : 0, 1, 2, 3 ... (non-negative)
An signed integral type can hold both negative and positive numbers: -27,- 3, 0, 42, 68 etc.

A floating point type can hold an approximation of a 'real' number - that is, a number which can have a fractional part: -3.87, 4.642, 768.0 etc.

You may skip over the details about machine-level representation of numbers for now (come back to it sometime later). For now, just follow the advice at the end of the section:
Advice: Deciding which Type to Use
C++, like C, is designed to let programs get close to the hardware when necessary. The arithmetic types are defined to cater to the peculiarities of various kinds of hardware. Accordingly, the number of arithmetic types in C++ can be bewildering.

Most programmers can (and should) ignore these complexities by restricting the types they use. A few rules of thumb can be useful in deciding which type to use:

• Use an unsigned type when you know that the values cannot be negative.

• Use int for integer arithmetic. ... If your data values are larger than the minimum guaranteed size of an int, then use long long.

• Do not use plain char or bool in arithmetic expressions. Use them only to
hold characters or truth values. ....

• Use double for floating-point computations....


Start writing your first programs as if the only arithmetic types are: unsigned int, int, double, bool and char.
Alright, there are a few things which seriously confuse me. I thought the type char holds a character - a single 'letter' (at least in java). Then why is it considered an arithmetic (integral) type?

Secondly, I've heard that C++ is quite close to the memory, and will have a lot to do with this bit and byte stuff. I really don't like saying "I'll come back to this later" because later it will cause more problems, as I didn't understand what was taught earlier. That being said, I totally agree with you, I shouldn't waste my time on one single topic. Later, lets say after I finish this chapter, can I message you to learn about bits, bytes and everything related to that discussed in this chapter? Thanks a lot.
> I thought the type char holds a character - a single 'letter'
> Then why is it considered an arithmetic (integral) type?

The type char is a byte; it holds a number. The number that it holds is typically the encoding for a single character.

For example, ISO/IEC 646 is widely used. https://en.wikipedia.org/wiki/ISO/IEC_646
As per this encoding, the character 'A' is represented as a byte with a numeric value of 65.

Read the next section in your book: 2.1.2 Type conversions and things would become clearer.


> Secondly, I've heard that C++ is quite close to the memory, and will have a lot to do with this bit and byte stuff.

C++ can, in situations where it is required, deal with this bit and byte stuff effectively. However, the vast majority of code that is written in C++ does not directly deal with it. There is a world of difference between a programming language that can be close to the machine when it wants, and a programming language that is (always) close to the machine.

From the preface of the book that you are reading:
Modern C++ can be thought of as comprising three parts:
• The low-level language, much of which is inherited from C
• More advanced language features that allow us to define our own types and to organize large-scale programs and systems
• The standard library, which uses these advanced features to provide useful data structures and algorithms

Most texts present C++ in the order in which it evolved. They teach the C subset of C++ first, and present the more abstract features of C++ as advanced topics at the end of the book. There are two problems with this approach: Readers can get bogged down in the details inherent in low-level programming and give up in frustration. Those who do press on learn bad habits that they must unlearn later.

We take the opposite approach: Right from the start, we use the features that let programmers ignore the details inherent in low-level programming. For example, we introduce and use the library string and vector types along with the built-in arithmetic and array types. Programs that use these library types are easier to write, easier to understand, and much less error-prone.


Stroustrup:
Even for the professional programmer, it is impossible to first learn a whole programming language and then try to use it. A programming language is learned in part by trying out its facilities for small examples. Consequently, we always learn a language by mastering a series of subsets. The real question is not ‘‘Should I learn a subset first?’’ but ‘‘Which subset should I learn first?’’

One conventional answer to the question ‘‘Which subset of C++ should I learn first?’’ is ‘‘The C subset of C++.’’ In my considered opinion, that’s not a good answer. The C-first approach leads to an early focus on low-level details. It also obscures programming style and design issues by forcing the student to face many technical difficulties to express anything interesting. C++’s better support of libraries, better notational support, and better type checking are decisive against a ‘‘C first’’ approach.


Koenig and Moo (Preface to Accelerated C++):
Our approach is possible only because C++, and our understanding of it, has had time to mature. That maturity has let us ignore many of the low-level ideas that were the mainstay of earlier C++ programs and programmers.
The ability to ignore details is characteristic of maturing technologies. For example, early automobiles broke down so often that every driver had to be an amateur mechanic. It would have been foolhardy to go for a drive without knowing how to get back home even if something went wrong. Today's drivers don't need detailed engineering knowledge in order to use a car for transportation. They may wish to learn the engineering details for other reasons, but that's another story entirely.

We define abstraction as selective ignorance--concentrating on the ideas that are relevant to the task at hand, and ignoring everything else--and we think that it is the most important idea in modern programming. The key to writing a successful program is knowing which parts of the problem to take into account, and which parts to ignore. Every programming langauge offers tools for creating useful abstractions, and every successful programmer knows how to use those tools.
...
If abstractions are well designed and well chosen, we believe that we can use them even if we don't understand all the details of how they work.

Hmm, seems like I have an older/newer edition of the book. 2.1.2 is Floating-Point Types, not Type Conversions.

So, in a nutshell, a char holds a number and cannot hold an alphabet?

Also, I'm really sorry to annoy you, but I honestly fail to understand bits and bytes. I know that at the machine level, the computer sees only 1s and 0s, and that is called a binary digit, and 8 of those make a byte, but really, I don't get more than that.
> seems like I have an older/newer edition of the book. 2.1.2 is Floating-Point Types, not Type Conversions.

I was referring to the section in C++ Primer, Fifth Edition


> So, in a nutshell, a char holds a number and cannot hold an alphabet?

A char holds a number which represents a character in the alphabet.

1
2
3
4
5
6
7
8
char c = 'A' ; // we can print this out as the character A
// We can think of c in two ways: 
// a. holding the character A 
// b. holding a number that has the numeric value of character A

int i = c ; // we can print this out as a number (like 65)

int j = c + 3 ; // 68, assuming that the 'number' for character A is 65 



> I know that at the machine level, the computer sees only 1s and 0s, and that is called a binary digit,
> and 8 of those make a byte, but really, I don't get more than that.

All that you need to know right now, in addition to what you already know is:
It is possible to interpret any sequence of 1s ans 0s as a number.
https://en.wikipedia.org/wiki/Binary_numeral_system
Hmm, seems like I have the Fourth Edition. Oh well.

I think I finally understand what they mean by integral types - these types contains numbers, which may represent something else (as in an alphabet or a truth value).

For example, true or false isn't directly a number and neither is an alphabet. However, they are still considered integral types as the NUMBERS REPRESENTING THEM count.

Please let me know if my explanation is correct.


All that you need to know right now, in addition to what you already know is:
It is possible to interpret any sequence of 1s ans 0s as a number.
https://en.wikipedia.org/wiki/Binary_numeral_system


With this, I will now proceed, reluctantly ignoring the binary stuff. Can you tell me when I can come back to this? As in, when will I have enough knowledge to understand those sections?

Sorry to annoy you so much, literally so much.

Regards,
GreatBlitz.
> Please let me know if my explanation is correct.

Yes.


> Can you tell me when I can come back to this?
> As in, when will I have enough knowledge to understand those sections?

You should come back to this when you start reading about bit-wise operators. (These are not commonly used operators, but the book will certainly be talking about them.)

In the Fifth edition, bit-wise operators are covered in section 4.8 and the sizeof operator in section 4.9. These may be covered in a different sequence in the fourth edition.

I just had a relook at your opening post; it appears that the book that you had actually ordered is the Fifth edition.
I have ordered this book - http://www.amazon.com/dp/0321714113 and it should be arriving in a few days.

If they had sent you the earlier edition against that order, you should get it replaced.
Hmm, I see the website shows edition 5. However I did not order it from Amazon, I got it from a local online bookstore. Looks like they didn't have the latest edition. I gave the link to Amazon because it was the first result on Google Search.

But it does seem that I am in luck. I was looking through the index, and in Edition 4, section 5.3 is Bitwise Operators, 5.8 is sizeof operator, and 5.12 is Type Conversions.

Will it make a big difference if it goes in this order? I mean, I really don't have much of a choice at this point sadly.
> Will it make a big difference if it goes in this order?

It would be best for you to follow the order that is in the edition that you are reading.


> I really don't have much of a choice at this point sadly.

Perhaps you do. If you had ordered the book without specifying the edition, they should either have given you the edition that is current or explicitly asked you first if you would be satisfied with an obsolete edition of the book.

I'm not aware of the the consumer protection laws in your country/province; perhaps you could demand that the book be replaced with the current edition or they accept the return of the book for a full refund.

It would be very worthwhile, getting the latest edition of this book.
The thing to note here is that they didn't have the Fifth Edition in the first place. If I were to order the book again from a different website, I would be spending more money, and I don't think my parents are okay with spending money on just two different editions of the same book.

Is the difference between the two editions notable, and will it have quite the adverse effect on the way I learn?

I really do think that I should get back to learning, rather than thinking about what edition to use. While I understand that the latest edition is more up to date, the fact that I have no access to the book puts me in a place where I might as well do with what I have, rather than grumble about it.

Thank you so much for your help so far. You have been of great aid to me. I will post back to this forum should I encounter a hurdle.

Regards,
GreatBlitz.
> Is the difference between the two editions notable

The fifth edition is more or less a complete rewrite. And it includes the additions incorporated into C++ in 2011.


> will it have quite the adverse effect on the way I learn?

No. Nothing that you learn using the earlier edition would be irrelevant or invalid.


Carry on learning from the book that you have with you right now; it is a good book.
Okay, here is one small thing - I didn't understand much from section 2.1 and 2.2. This means all the content on these two pages (use these pages, not your book - remember, you have the fifth edition)
http://flylib.com/books/en/2.674.1.20/1/
http://flylib.com/books/en/2.674.1.21/1/

Here is what I did understand.

The types are:

Numbers
1) short - small size
2) int - ordinary size
3) long - large size, often same as int

Type to be used generally - int.

Decimals
1) float - small size
2) double - ordinary size
3) long double - large size

Type to be used generally - double.

Characters
1) char - single character
2) wchar_t - extended character support, but still single character
3) string - array of chars put together

Boolean - true or false.

Signed - both negative, positive values allowed. (0 included)
Unsigned - only greater of equal to 0.

Can you just skim through the pages I linked to, and tell me if I'm gonna be fine with what I know already? @JLBorges

Regards,
GreatBlitz.
Last edited on
It seems fine.

In the terminology that you used, 'Numbers' are whole numbers (integers) and
'Decimals' are floating point numbers (approximation of numbers with a fractional part).

C++11 adds the integral types long long and unsigned long long
See 'Fundamental data types' on this page: http://www.cplusplus.com/doc/tutorial/variables/


Section 2.2 talks about literal constants:

Boolean: true, false
Character: 'a', 'f', '\n' etc.
Integer: 20 (int) , 346LL (long long), 23U (unsigned int) etc.
Floating point: 2.36 (double), 2.3f (float)
String literal: "GreatBlitz", "Hello World!"

For more information and examples, have look at: http://www.cplusplus.com/doc/tutorial/constants/
Right, got that.

I simply can't seem to find any solutions to exercises to confirm my answers. There was a website for Chapter 1, but couldn't find one for Fourth Edition Chapter 2.

Is this:
char _;
a valid variable? Can a name be just an underscore?

What about this:
float Float = 3.14f;
float is not a valid identifier, but is Float (with an uppercase F)?

Also, have a look at these:

Exercise 2.15:
What, if any, are the differences between the following definitions:
int month = 9, day = 7;
int month = 09, day = 07;

If either definition contains an error, how might you correct the problem?

My answer: Neither definition is erroneous, however, the first initialization refers to the decimal numbers 9 and 7 and the second one refers to the octal numbers.


Exercise 2.16:
Assuming calc is a function that returns a double, which, if any, of the following are illegal definitions? Correct any that are identified as illegal.
(a) int car = 1024, auto = 2048;
(b) int ival = ival;
(c) std::cin >> int input_value;
(d) double salary = wage = 9999.99;
(e) double calc = calc();

My answer:

(a) is valid.

(b) is invalid; ival has no value yet, can't be assigned to itself. Not sure how to correct it.

(c) is invalid, variable cannot be created in the cin statement. It should be:
int input_value;
std::cin >> input value;

(d) is invalid. Assuming wage has not been initialized, the statement should be:
double salary = double wage = 9999.99;

(e) really not sure about this one. I'm guessing it is valid though.
Last edited on
> I simply can't seem to find any solutions to exercises to confirm my answers.

Use the C++ compiler; it can give you quite a bit of information.
Have it open by your side as you do the exercises, type in code, try to compile the code; experiment.
Exercise 2.15 http://coliru.stacked-crooked.com/a/be5b6393186ffe1c

Exercise 2.16:

(a). error: auto is a keyword.

(b). is a logical error; we are trying to initialise ival with its own uninitialised value.
To correct it: int ival = 100 ; // fine

You are right about (c)

(d) is fine if wage was declared earlier.
This is invalid: double salary = double wage = 9999.99;
This would be a good time to try compiling it. What does the compiler say if you type this in?
1
2
3
4
int main()
{
     double salary = double wage = 9999.99;
}

Howto: http://www.cplusplus.com/doc/tutorial/introduction/codeblocks/

(e) double calc = calc(); is an error. The name of the function calc() is hidden by the name of the local variable calc()
To correct it, give a different name to the local variable: double result = calc() ;
For (d), I get two errors:
error: expected primary-expression before 'double'
error: expected ',' or ';' before 'double'
Yes. double wage = 9999.99; is not an expression.

Now try:
1
2
3
4
5
int main()
{
     double wage ; // uninitialised
     double salary = wage = 9999.99;
}
Yep, no compile errors. I can guess why this happens - a new variable as well as an old variable are being assigned to the literal constant 9999.99.

But what I can't understand is why you said this - Yes. double wage = 9999.99; is not an expression. Why isn't it?
An expression is something that is evaluated and yields a result.

int i = 23 ; is not an expression; it defines a variable and initialises it.

i + 7 is an expression; when evaluated it yields 30 as the result.
i = 45 is an expression; the = here is assignment, not initialisation. When evaluated, it assigns the value 45 to i and yields the result i.

Let it be for the moment; wait till you come to the topic 'expressions' (It is chapter 4 in the fifth edition.)
Last edited on
JLBorges wrote:
int i = 23 ; is not an expression; it defines a variable and initialises it.
I beg to differ:
http://ideone.com/CrXuFZ
Useful for opening files:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if(std::ifstream in ("in.txt"))
{
    int x;
    if(in >> x)
    {
        std::cout << x << std::endl;
    }
    else
    {
        std::cout << "in.txt does not start with a number" << std::endl;
    }
}
else
{
    std::cout << "Cannot read from in.txt" << std::endl;
}
Though, I will accept that this is a special case in C++'s syntax and cannot be used in all places an expression can be used.
Last edited on
Pages: 12345