Skip to main content
GameDev.net gamedev.net
📌 Pinned 🔒 Locked

C++ Workshop - Expressions & Statements (Ch. 4)

Started by JWalsh Jun 19, 2006 at 11:28 AM 41 replies 32.7k views
Original Post
JWalsh
JWalsh

Welcome to the GDNet C++ Workshop – Ch. 4

For a complete introduction to this workshop, please look here. Workshop Overview This workshop is designed to aid people in their journey to learn beginning C++. This workshop is targeted at highly motivated individuals who are interested in learning C++ or who have attempted to learn C++ in the past, but found that without sufficient support and mentoring they were unable to connect all the pieces of this highly complex but powerful programming language. This is a 'guided' self-teaching C++ workshop. Each student is responsible for taking the time to read the material and learn the information. The community and tutors that arise out of this workshop are here for making the learning process run more smoothly, but are not obligated to baby-sit a person's progress. Because everyone will be working from the same textbook (Teach Yourself C++ in 21 days 5th Ed.), students may find it easier to get answers to the specific questions they might have. There is no minimum age requirement, and there is no previous programming experience required. Additionally, this workshop does not attempt to defend C++ as a language, nor does it attempt to demonstrate that C++ is either more or less useful then other programming languages for any particular purpose. People who intend to start a discussion about the differences between C++ and ANY other languages (except as are relevant to a particular discussion), are encouraged to do so elsewhere. This workshop is for educational, not philosophical discussions. Quizzes & Exercises Each week will have quizzes and exercises posted in the weekly threads. Please try and answer them by yourself. As well, please DO NOT post the answers to Quizzes and Exercises within this thread. Once it becomes acceptable to post the answers to quizzes and exercises, an additional thread will be created each week specifically for the purpose of posting quiz answers. If you try with reasonable effort but are unable to answer the questions or complete the exercises, feel free to post a clarification question here on the thread. Tutors, myself, or others will do the best we can to point you in the right direction for finding the answer.

Chapter 4 – Creating Expressions and Statements

Introduction Greetings! Welcome to what might be considered the most fundamental chapter in the book - expressions and statements. Although basic layout and variables are an integral part of C++, even assigning a value to a variable is a statement. As well, expressions are the "number crunching" component of the language, and this is especially useful for game development. Any time a vehicle moves a velocity (v) over a time (t) it's going to travel some distance (x). Any time a person animates, or an object shows up in 3d space, or even in 2d space...we're using math. Expressions are how we do math in C++. Additionally, we will cover the 'if' statement in this chapter. Up until this point your exercises and programs have done exactly one "thing." The introduction of branching means your programs can now take different paths of execution. Beginning this week you will be given more "exercises" than before as it now possible to actually code something useful. This chapter is approximately 30 pages - not counting the summary, questions and exercises. Roughly half way through the week myself, tutors, or anyone else simply wishing to challenge their teammates learning C++ can post review and quiz questions in this thread. Please do not post the answers in this thread however, as a new thread will be created for that purpose. Outline of the Reading
  1. Starting with Statements
  2. Expressions
  3. Working with Operators
  4. Combining Assignments and Mathematical Operators
  5. Incrementing and Decrementing
  6. Understanding Operator Precedence
  7. Nesting Parentheses
  8. The Nature of Truth
  9. The 'if' Statement
  10. Using Braces in Nested 'if' Statements
  11. Using the Logical Operators
  12. Short Circuit Evaluation
  13. Relational Precedence
  14. More about Truth and Falsehood
  15. The Conditional (Ternary) Operator
Additional Resources None... Weekly Errata None... [Edited by - jwalsh on May 30, 2007 1:09:44 PM]
Mitsukai
Mitsukai
hi there,
i was just wondering where i could go to read information and posts on the previous chapters of this workshop because i want to start learning c++ but i cant start it until my exams are over at the end of the month.
will i be able to catch up to everybody if i start it then?
JWalsh
JWalsh
Mitsukai,

I'm glad you're with us. Let us know if you have any other questions.

If you follow the bread-crumb at the top of the thread back a bit you'll see that it takes you to the CPP Workshop forum. This is where you can find the previous chapters. The bread-crumb trail looks like this:

'Home » Community » Forums » CPP Workshop » C++ Workshop - Week 3 (Ch. 4)'

Additionally, if you go to the main forums page and scroll to the VERY bottom, you'll find the CPP Workshop. Rather than putting this workshop in the technical section, it was decided by the staff to keep it at the bottom.

Finally, you can just look Here.

Cheers!
CondorMan
CondorMan
A couple of "clarification" questions:

Firstly, on page 70, it states: "An operator is a symbol that causes the compiler to take an action". The compiler, with the linker, convert source code to an executable program. Surely mathematical operators work within the executable? If the source code says "a = b + 2;" or "a = b - 2;", that happens when the executable runs, rather than having an effect on the compiler? Aren't the compiler and linker acting as an "interpreter" to translate (for instance) French to Russian?

Secondly, an "if statement" is of the form:

if (expression)
statement;

and if there are several lines in the statement, it is replaced by a block bounded by {}. I don't think that there should be a semi-colon after the } so which is correct, the example on line 40 of Listing 4.4 or at the end of the grey section on page 83? Are they both correct and, if so, under what circumstances is one or the other used?
JWalsh
JWalsh
Quote:

Firstly, on page 70, it states: "An operator is a symbol that causes the compiler to take an action". The compiler, with the linker, convert source code to an executable program. Surely mathematical operators work within the executable? If the source code says "a = b + 2;" or "a = b - 2;", that happens when the executable runs, rather than having an effect on the compiler? Aren't the compiler and linker acting as an "interpreter" to translate (for instance) French to Russian?


I'm a bit confused by this. What are you asking exactly? I cant figure out which part of the above is a statement and which part you're confused about. If I go strictly by ? marks, then the answers would be something like this.

When you build your executable all that remains are 1's and 0's. There are no equal signs, subtraction signs, etc...The 1's and 0's represent instructions for the processor to do things, such as move a value into a registry, move a value from one place in memory to another, and to take two values in the current registries, add them together, and output the results to a third registry. This process of working with registries, and performing mathematical calculations is at the core of everything a program does.

Operators in your C++ code are usually converted directly in to "Opcodes" or processor instructions. 'Add' for example has a matching processor instruction which has a matching Assembly instruction ADD, which happens to have an opcode of somewhere between 00 and 08. Whenever your compiler/linker encounters the + operator, it compiles it into the appropriate opcodes to instruct your processor to add values together.

Compilers don’t translate French to Russian. They 'compile' C++ into binary instructions which your processor understands. This is more than just a strict copy/paste of values, it involves symbolic matching, creation of opcodes, and addressing of memory locations within the instructions.

Originally people programmed in 1's and 0's. By 1's and 0's we really mean opcodes. Values which the processor recognized as being symbolic for an instruction and arguments. After which we decided there wasn’t any good formatting and the opcodes were all difficult to remember. So assembly was created. Assembly instructions are really just aliases for opcodes and the assembler takes your .asm file and "assembles" it. There is still a conversion into binary, but its not as complicated as the leap from C++ to binary.

Finally, we created "high level" languages such as C++ to make the code more 'readable' by humans. If I didn’t answer your question, can you re-post with a clarification. I really am finding it difficult to determine what you're asking.

Quote:

Secondly, an "if statement" is of the form:

if (expression)
statement;

and if there are several lines in the statement, it is replaced by a block bounded by {}. I don't think that there should be a semi-colon after the } so which is correct, the example on line 40 of Listing 4.4 or at the end of the grey section on page 83? Are they both correct and, if so, under what circumstances is one or the other used?


Technically, an 'if statement' is either of the two formats:

if( expression) statement;

OR

if( expression ) { }

However, the ';' is the character identifying the end of a statement, so putting it in at the end of a {} block does not constitute a compiler error. That is, the following is perfectly acceptable, though non-standard, and not common syntax:

if( expression ) { };

In other words, the grey section on page 83 is probably a "typo," but is still legal syntax.

Cheers!
CondorMan
CondorMan
Thank you.

I agree that I did ramble a bit!

I thought that it was an error when it said that "An operator is a symbol that causes the *compiler* to take an action". I was under the impression that a compiler (and linker) convert source code to a series of 0's and 1's that the computer understands and the operator made the *computer* take an action (i.e. adding two numbers) when the executable is run.

I appreciate the clarification about the unusual, but legal, syntax of a semi-colon following a closing curly bracket.
Zahlman
Zahlman
Just thought I'd contribute a tidbit here although I didn't sign up as a tutor. The below is written with no attempt to sugar-coat or take things slowly, and is pretty optional reading, but if you're willing to put in the effort I hope and expect you will find it useful :)

Usually, the set of statements following an if-condition are called a 'block' or 'suite' of statements. Every sort of block (i.e. matching pairs of {}, except for the ones used for initializing arrays) introduces its own scope for variables. The block terminates the if-statement; there is no need for a semicolon.

The scope is terminated by a close brace, after which whatever sort of statement/function body/etc. would normally be legal can begin. You *can*, as noted, put a semicolon after the close brace, but normally you wouldn't ever (it *looks* wrong, and never serves a purpose). The reason you can do this is because the semicolon simply indicates an empty statement (all zero 'tokens' between the close brace and semicolong), which is legal (and does nothing).

The reason you need a semicolon after a *class* declaration is because the declaration of a class is *not* terminated by the block, but by a semicolon. The class-declaration statement also allows you to specify global instances at the end: it's as if you'd written "typedef int myClass; myClass foo, bar;", except that you insert the definition of the myClass type in-line (within the braces) into that declaration of foo and bar. Normally, you don't want to use this feature (for one thing, because you're making instances, you'll have linking problems if you put it in the header; but if you put it in the cpp instead, other classes don't see your class's interface), but it's there for C backwards compatibility.
rip-off
rip-off
Also note that:

if( someCondition ){    // do stuff};


will compile, but:

if( someCondition ){    // do stuff};else{    // do other stuff}


won't.
Personal_Worker
Personal_Worker
Hello, i'm new here..

i wanna join this workshop since i saw it's very useful for me..

and now i'm trying to pursuit until reached chapter 4..

i hope people here will always help me as a newbie to study c++

thanks
Emmanuel Deloget
Emmanuel Deloget
Quote:
Original post by Personal_Worker
Hello, i'm new here..

i wanna join this workshop since i saw it's very useful for me..

and now i'm trying to pursuit until reached chapter 4..

i hope people here will always help me as a newbie to study c++

thanks


It is our goal to help you - don't worry, we'll be there. Feel free to post any question you have ;)

Regards,
twoaterisn
twoaterisn
so

int main(){;;;;return 0;}


is legal, but just means "do nothing four times" if I get the "if(){}; issue" right?
Myotis
Myotis
Hello, ( Its not about chapter 4 )
Since the beginning, all the programs we do are executed in the DOS panel. I was wondering if during this workshop we are gonna build programs that use interface. Like, printing "Hello World!" in black letters on a white screen rather than in the DOS command windows. Is this part of the book and if so which day is it ?

Thank You.
Oluseyi
Oluseyi
Quote:
Original post by Myotis
Since the beginning, all the programs we do are executed in the DOS panel. I was wondering if during this workshop we are gonna build programs that use interface. Like, printing "Hello World!" in black letters on a white screen rather than in the DOS command windows. Is this part of the book and if so which day is it ?

Strictly speaking, graphical user interfaces are not a feature of C++. You need a library that enables you to generate GUIs for specific target platforms. For Windows the base library is the Win32 C API. For X-Window System workstations, it's Xlib. For Mac OS X, it's Cocoa, with a bit of Objective-C for binding purposes.

It's outside the scope of learning the C++ language.
kaydash
kaydash
I have'nt read Day 4 yet, so I'll be catching up with everyone by this weekend, once I've gotten through Day 2 and Day 3.(This workshop is turning out to be more useful then I had imagined, perhaps we will be working on GUIs SOON!!!!)
I Have Awoken.
JWalsh
JWalsh
Quote:
Original post by kaydash
I have'nt read Day 4 yet, so I'll be catching up with everyone by this weekend, once I've gotten through Day 2 and Day 3.(This workshop is turning out to be more useful then I had imagined, perhaps we will be working on GUIs SOON!!!!)


This workshop will not be covering Graphical User Interfaces. As Oluseyi already pointed out, GUI Interfaces are something you USE the C++ language to create, they are not inherently part of the language. Generally speaking you use one of a number of available Libraries or API's to assist you in the creation of your GUI's. The scope of this workshop is only the C++ language syntax and semantics.

The Win32 API, or the .NET Framework using C++/CLR is a subject for a later workshop.


(Nobody should ever be forced to learn MFC) [wink]


Cheers!
Oluseyi
Oluseyi
Quote:
Original post by jwalsh

(Nobody should ever be forced to learn MFC) [wink]

[opinion]
Except as an illustration of bad design and the consequences of working around the pre-Standardization limitations of a programming language.
[/opinion]

Seriously, AFX_BEGIN_MESSAGE_MAP? *shudder*
Stephen R
Stephen R
Quote:
Original post by twoaterisn
so

*** Source Snippet Removed ***

is legal, but just means "do nothing four times" if I get the "if(){}; issue" right?


Yup. It is exactly equivilent to the same code without those four ";" lines.

[ADVANCED]
This is probably slightly beyond the scope of this course, and requires some knowledge of assembly, but it is sometimes handy to see what your code looks like in assembly, and how it compares to similar code to get a better feeel for how your code works on a lower level.

You can get to Visual C++ to output the assembler listings when compiling. This will allow you to see how different pieces of similar code differ from one another. You can make it do this by changing the assembler options output in your project settings in "Common Propperties -> C/C++ -> Output Files -> Assembler Output". After changing that option to "Assembly-Only Listing", when you compile your program, which is made of say main.cpp, it will put a file called main.asm in the same output directory as your executable by default.

I do not recommend this for anyone who doesn't know assembly, and due to the optimized nature of the produced assembly it will only be useful for certain types of issues. But since this is one of them I thought I'd mention it. Also keep in mind that the asm produced by a compiler is unique to that compiler, each one can produce different asm for the same code.
[/ADVANCED]
JWalsh
JWalsh
Greetings All!

Sorry I was unable to post a quiz yesterday, I was unfortunately preoccupied for the majority of the day. However, it's once again QUIZ TIME!!! That's right, listed below are a set of quiz questions to help you test your knowledge and understanding of the material contained in chapter 4. Each chapter builds upon the knowledge obtained in previous chapters, so it can be dangerous and confusing to advance to later chapters without a complete understanding of the material already covered.

NEW: At the end of the chapter quiz you’ll also find chapter exercises. This is new to the weekly quiz, and is now an option because you’ve learned enough information to write useful programs.

In addition to the questions and exercises below, make sure that as you're reading the book you enter the examples into your compiler, build the program, and run the executable. I know this is a time consuming process, but the repeat use of keywords, syntax, and semantics will help ingrain the information into your long-term memory. My advice is to create a simple "driver" project with a function main. As you read, enter the examples into function main, test it, and then erase it for use again in the next example.

PLEASE DO NOT POST THE ANSWERS TO THESE QUESTIONS OR EXERCISES. If you are unable to answer these questions, please ask for assistance, but DO NOT POST THE ANSWERS. Any question which is not marked with [Extra Credit] can be answered by reading your textbook. Questions which are marked [Extra Credit] either have been answered in the thread previously, or can be answered by doing a bit of research.

A new thread will be created in a day or two for you to post your answers to these question.

Chapter 4 Quiz

1. What do statements do in C++?
2. Where can you put a compound statement?
3. What’s another name for a compound statement?
4. What syntax identifies the beginning and ending of a block?
5. What is an expression in C++?
6. Which side of the equal operator can an expression ALWAYS be on? Why not the other side?
7. What do operators act upon?
8. Can an expression be acted upon by operators?
9. What does the assignment operator do?
10. What is an r-value and an l-value? How does this relate to question 6 above?
11. What are the 5 mathematical operators and what do they do? Give examples of inputs and outputs.
12. What happens when you subtract a large unsigned number for a smaller unsigned number?
13. [Extra Credit]What is integer truncation? How can it be avoided?
14. What are the increment/decrement operators, and how are they used. Show examples.
15. What is the difference between prefix and postfix increment/decrement? What are the results? Show examples.
16. What is the precedence of the mathematical operators?
17. Are the operators left-to-right or right-to-left?
18. What about the assignment operator?
19. What operator can ALWAYS be used to change the precedence of an expression?
20. How are nested parentheses read? Show examples.
21. Can all expressions be evaluated for their truth?
22. What data type is exclusively for truthiness? (tip of the hat to Stephen Colbert)
23. What is the ANSI standard size of that data type?
24. What are the six relational operators? Show examples of what values they return with different inputs.
25. What does an ‘if’ statement do?
26. When is an if-block executed, when is it skipped?
27. What does an ‘else’ statement do?
28. When is an else-block executed, when is it skipped?
29. [Extra Credit] What does an ‘else if’ statement do? When is it executed and when is it skipped?
30. What are the 3 logic operators in C++? How are they used? Show examples.
31. What is “Short Circuit Evaluation?” How might it be beneficial?
32. What is the precedence of the logical and conditional operators?
33. What is the conditional operator? How is it used? When might it be useful? Show examples.

Chapter 4 Exercises

1. The equation for distance traveled (dist) with a constant velocity is equal to the rate of movement (rate) multiplied by the time interval (time) traveling. (dist=rate*time) Write a program which prompts the user for rate and time, computes the distance traveled, and then outputs the result to the screen.

2. Write a program that knows a secret number and prompts the user to guess the number. When the user enters the number the program should notify the user whether the number guessed was too high, too low, or juuust right. We will modify this program later when we’ve covered loops in order to allow the user to guess until they get the correct answer or run out of tries. Additionally, we will cover random number generation when we explore functions next week.

Cheers and Good luck!

Gambler
Gambler
I would also like to say ‘thank you’ to everyone for the work you are putting into this.

The availability of professional programmers to answer questions is an enormous help, even if it is just a boost in confidence for right now. Knowing that there are professionals who make thoughtful, detailed, and precise posts in regards every question I have seen posted to date, gives me a lot of confidence that when we get to the meatier chapters I will not be wandering aimlessly.

$22 for a 900+ page book is a small price to pay for the skills I am already getting out of this, and there are still 17 more chapters!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.