C++ Workshop - C++ Keywords, Variables, & Constants (Ch. 3)

Started by
65 comments, last by Dbproguy 15 years, 11 months ago

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

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 specificaly 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 3 – Working with Variables and Constants

Introduction Greetings! This week we will be covering chapter 3 on variables and constants. The chapter is approximately 20 pages not including the summary, Q&A, and quiz questions at the end of the chapter. 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. This is a shorter week, only 7 days instead of 10 and at the beginning of the next week (Monday morning) we will again move on, so try and keep up. Participants are welcome to post their questions for this chapters within this thread and myself, the tutors, and other participants will do the best we can to answer your questions. As the thread is likely to grow to a hundred or more posts, the C++ workshop threads will be closely moderated. Discussions which become narratives, flame-wars, or philosophical will either be removed or moved to another forum, unless entirely relevant to the current chapters. Finally, feel free to post quiz-like questions here in this thread after about 3 days. This will give people an opportunity to test their knowledge and understanding after they’ve had a chance to absorb the information. For questions which require further research then what is in the book, mark the question with an [Extra Credit] tag. Topical Outline of the Reading (Not literal due to copyrights)
  1. Exploring the parts of a variable
  2. How Data is stored in memory
  3. Looking at size and range modifiers
  4. Exploring the standard C++ data types
  5. The nuances of creating variables
  6. C++ keywords which cannot be used as identifiers
  7. Working with variables
  8. Aliases
  9. Overflow/Underflow & Range limitations
  10. Interpreting integers as characters
  11. Special Characters
  12. Using constants
  13. Using enumerations
[Edited by - jwalsh on May 30, 2007 5:28:49 PM]
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
Advertisement
Hello all,

Quick question about literal constants. I've read the section in the book and I've become a bit confused. The following code:

int myAge = 39;

according to the book, is a literal constant. It also states that I can't change this value. Yet just eight pages earlier it uses this exact same method for assigning values to variables (or, at least, I think it's the same...???)

I'm sure I'm just missing something here. How exactly is this different from creating a variable and assigning a value to it?
The literal constant in the above line of code is the "39". It is a constant in that its value cannot be changed, and it litterally stands for the value 39. myAge can be assigned another value. If you wanted to permanently assign 39 to my age, you would write
const int myAge = 39;

The const keyword is short for "constant". If you tried to assign a new value to myAge after it had been declared constant, you would recieve a compile-time error.
------------------------------Support the Blue Skies in Games Campaign!A blog... of sorts.As a general rule, if you don't have a general rule in your signature, you aren't as awesome as someone who does. General rules roxor teh big one one ones.
I saw that too, about the literal constant.

I would like that clarified as well, but from what I could understand they were referring to the number 39 being a literal constant, not myAge.
Correct. 39 is the literal constant. You can't change the value of 39. You can however change the value of myAge, unless it has been declared const, as programwizard pointed out.

[warning]
More importantly, string literals like "Hello World" also are literal constants. Trying to modify them is a very common error. You will hear more about it when we discuss pointers, arrays and strings.
[/warning]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Hi,
I have a question regarding variable types. I understand how they work for numbers ( either int float or the others ) but what about letters ? char can store one character, a number or a letter but only one... How can I ask the user to input his name via cin>> ? With char Myname, Myname will only store the first letter of the name.

Thanks.
Quote:literal:
  • actual: being or reflecting the essential or genuine character of something; "her actual motive"; "a literal solitude like a desert"- G.K.Chesterton; "a genuine dilemma"

  • without interpretation or embellishment; "a literal depiction of the scene before him"

  • limited to the explicit meaning of a word or text; "a literal translation"

  • avoiding embellishment or exaggeration (used for emphasis); "it's the literal truth"

int myAge = 39;

myAge can not be a literal, even when it is made const, for the simple fact that it is a variable. Looking at it in source code does not tell you its value; you must evaluate it first.

C has a pair of interesting terms used to refer to the two sides of an expression. An lvalue (literally, "left value") is any object that can appear on the left hand side of an assignment while an rvalue is one that can appear on the right hand side. Virtually all lvalues are also rvalues; literals are objects that can only ever, throughout the entire program code, be rvalues. Even const objects appear as lvalues at point of initialization.
Quote:Original post by Myotis:
Hi,
I have a question regarding variable types. I understand how they work for numbers ( either int float or the others ) but what about letters ? char can store one character, a number or a letter but only one... How can I ask the user to input his name via cin>> ? With char Myname, Myname will only store the first letter of the name.

Thanks.


C++ has a built-in string class for handling strings of characters. You only have to include the string header file:
#include <iostream>#include <string>using namespace std;int main(){	string myName;	cin >> myName;	cout << myName;	return 0;}

This will allow the user to input a series of characters, and then print the result. Once you include the string header file, you can use string like a normal data type (note that if you don't use the namespace std, you will need to declare strings as std::string).
------------------------------Support the Blue Skies in Games Campaign!A blog... of sorts.As a general rule, if you don't have a general rule in your signature, you aren't as awesome as someone who does. General rules roxor teh big one one ones.
Quote:Original post by Myotis
Hi,
I have a question regarding variable types. I understand how they work for numbers ( either int float or the others ) but what about letters ? char can store one character, a number or a letter but only one... How can I ask the user to input his name via cin>> ? With char Myname, Myname will only store the first letter of the name.

Thanks.

Fruny has intimated that this will be covered in significant detail soon, but here's the quick answer:

C supports the notion of arrays, though not as a true first-class type. In C, strings are represented using null-terminated character arrays, meaning regular arrays of char with a null character (0, '\0') signifying the end of the string. Unfortunately, this requires that you constantly monitor the size of your string, maintain the length of your string separately from the string itself and otherwise babysit everything pertaining to strings, thus making string handling a rather tedious affair in C.

Standard C++ supplants this by providing the std::string type. Internally, std::string uses arrays, but there is no need for them to be null-terminated as a std::string stores its own length. Being a class, it also provides a number of member functions and operator overloads that make using strings in C++ intuitive and secure.

// C language example of string handling#include <stdio.h>#include <string.h>char name[1024];int length = 0;int main(){  printf("Please enter your name: ");  scanf("%s", &name);  length = strlen(name);// Comment about the following line after the examples  printf("The name you entered was: %s\n"         "The length of the name was: %d characters\n", name, length);  return 0;}

// C++ language example of string handling#include <iostream>#include <string>int main(){  using namespace std;  string name;  cout << "Please enter your name: ";  cin >> name;  cout << "The name you entered was: " << name       << "\nThe length of the name was: " << name.length()       << endl;  return 0;}


Two interesting things about the C example. One is that C's output functions required you to know the appropriate format specifier (%s, %d, etc) for the type of data you wanted to output as part of the same printf statement. Blech.

The second is that I have two string literals that are basically adjacent to each other (whitespace is meaningless to the C and C++ compilers), and C concatenates them into one string literal. It's an easy way to make your programs prettier. [smile]

(Okay, that may have been too much for the beginning stages of this workshop...)
I need to get my head around some terminology. This doesn't relate specifically to this week and I wasn't sure if I should put this into the "Introduction" thread. I know that it will come up eventually but wonder if a simple structure can be offered at this stage.

We've worked extensively with the iostream header file and that's needed to allow us to access cin, cout etc. but we also need the standard namespace to allow us to access them. It strikes me that there is a hierarchy, starting with C++ Language at the top but what's the order beneath that? There are namespace, objects, classes, header files etc. so, for instance, is the standard namespace part of the iostream header file or the other way around? How do they relate to each other?

A further question relates to other header files (as mentioned by Oluseyi): if iostream is needed to access cin, cout etc., where can a list of all available commands or keywords be obtained, along with their respective header file? In order to use "string name;" in the source code, "#include <string>" must precede it. Sure, this will come with with experience and familiarity with the language but I suspect that there's a list somewhere.

Thank you.

This topic is closed to new replies.

Advertisement