`
universsky
  • 浏览: 91279 次
文章分类
社区版块
存档分类
最新评论

C++ Variables. Data Types.

 
阅读更多

Variables. Data Types.

The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting program just to obtain a simple sentence written on the screen as result. It certainly would have been much faster to type the output sentence by ourselves. However, programming is not limited only to printing simple texts on the screen. In order to go a little further on and to become able to write programs that perform useful tasks that really save us work we need to introduce the concept of variable.

Let us think that I ask you to retain the number 5 in your mental memory, and then I ask you to memorize also the number 2 at the same time. You have just stored two different values in your memory. Now, if I ask you to add 1 to the first number I said, you should be retaining the numbers 6 (that is 5+1) and 2 in your memory. Values that we could now -for example- subtract and obtain 4 as result.

The whole process that you have just done with your mental memory is a simile of what a computer can do with two variables. The same process can be expressed in C++ with the following instruction set:

1
2
3
4
a = 5;
b = 2;
a = a + 1;
result = a - b;


Obviously, this is a very simple example since we have only used two small integer values, but consider that your computer can store millions of numbers like these at the same time and conduct sophisticated mathematical operations with them.

Therefore, we can define a variable as a portion of memory to store a determined value.

Each variable needs an identifier that distinguishes it from the others. For example, in the previous code the variable identifiers were a, b and result, but we could have called the variables any names we wanted to invent, as long as they were valid identifiers.

Identifiers

A valid identifier is a sequence of one or more letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters, digits and single underscore characters are valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character (_ ), but in some cases these may be reserved for compiler specific keywords or external identifiers, as well as identifiers containing two successive underscore characters anywhere. In no case can they begin with a digit.

Another rule that you have to consider when inventing your own identifiers is that they cannot match any keyword of the C++ language nor your compiler's specific ones, which are reserved keywords. The standard reserved keywords are:

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while

Additionally, alternative representations for some operators cannot be used as identifiers since they are reserved words under some circumstances:

and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

Your compiler may also include some additional specific reserved keywords.

Very important: The C++ language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers.

Fundamental data types

When programming, we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way.

The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in C++. A byte can store a relatively small amount of data: one single character or a small integer (generally an integer between 0 and 255). In addition, the computer can manipulate more complex data types that come from grouping several bytes, such as long numbers or non-integer numbers.

Next you have a summary of the basic fundamental data types in C++, as well as the range of values that can be represented with each one:

Name Description Size* Range*
char Character or small integer. 1byte signed: -128 to 127
unsigned: 0 to 255
short int (short) Short Integer. 2bytes signed: -32768 to 32767
unsigned: 0 to 65535
int Integer. 4bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
long int (long) Long integer. 4bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
bool Boolean value. It can take one of two values: true or false. 1byte true or false
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t Wide character. 2 or 4 bytes 1 wide character

* The values of the columns Size and Range depend on the system the program is compiled for. The values shown above are those found on most 32-bit systems. But for other systems, the general specification is that int has the natural size suggested by the system architecture (one "word") and the four integer types char, short, int and long must each one be at least as large as the one preceding it, with char being always one byte in size. The same applies to the floating point types float, double and long double, where each one must provide at least as much precision as the preceding one.

Declaration of variables

In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float...) followed by a valid variable identifier. For example:

1
2
int a;
float mynumber;


These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the identifier mynumber. Once declared, the variables a and mynumber can be used within the rest of their scope in the program.

If you are going to declare more than one variable of the same type, you can declare all of them in a single statement by separating their identifiers with commas. For example:

int a, b, c;


This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as:

1
2
3
int a;
int b;
int c;


The integer data types char, short, long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero). This can be specified by using either the specifier signed or the specifier unsigned before the type name. For example:

1
2
unsigned short int NumberOfSisters;
signed int MyAccountBalance;


By default, if we do not specify either signed or unsigned most compiler settings will assume the type to be signed, therefore instead of the second declaration above we could have written:

int MyAccountBalance;


with exactly the same meaning (with or without the keyword signed)

An exception to this general rule is the char type, which exists by itself and is considered a different fundamental data type from signed char and unsigned char, thought to store characters. You should use either signed or unsigned if you intend to store numerical values in a char-sized variable.

short and long can be used alone as type specifiers. In this case, they refer to their respective integer fundamental types: short is equivalent to short int and long is equivalent to long int. The following two variable declarations are equivalent:

1
2
short Year;
short int Year;


Finally, signed and unsigned may also be used as standalone type specifiers, meaning the same as signed int and unsigned int respectively. The following two declarations are equivalent:

1
2
unsigned NextYear;
unsigned int NextYear;


To see what variable declarations look like in action within a program, we are going to see the C++ code of the example about your mental memory proposed at the beginning of this section:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// operating with variables

#include <iostream>
using namespace std;

int main ()
{
  // declaring variables:
  int a, b;
  int result;

  // process:
  a = 5;
  b = 2;
  a = a + 1;
  result = a - b;

  // print out the result:
  cout << result;

  // terminate the program:
  return 0;
}
4


Do not worry if something else than the variable declarations themselves looks a bit strange to you. You will see the rest in detail in coming sections.

Scope of variables

All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int.

A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.


Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.

The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa.

Initialization of variables

When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There are two ways to do this in C++:

The first one, known as c-like initialization, is done by appending an equal sign followed by the value to which the variable will be initialized:

type identifier = initial_value ;
For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write:

int a = 0;


The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (()):

type identifier (initial_value) ;
For example:

int a (0); 


Both ways of initializing variables are valid and equivalent in C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// initialization of variables

#include <iostream>
using namespace std;

int main ()
{
  int a=5;               // initial value = 5
  int b(2);              // initial value = 2
  int result;            // initial value undetermined

  a = a + 3;
  result = a - b;
  cout << result;

  return 0;
}
6


Introduction to strings

Variables that can store non-numerical values that are longer than one single character are known as strings.

The C++ language library provides support for strings through the standard string class. This is not a fundamental type, but it behaves in a similar way as fundamental types do in its most basic usage.

A first difference with fundamental data types is that in order to declare and use objects (variables) of this type we need to include an additional header file in our source code: <string> and have access to the std namespace (which we already had in all our previous programs thanks to the using namespace statement).

1
2
3
4
5
6
7
8
9
10
11
// my first string
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string mystring = "This is a string";
  cout << mystring;
  return 0;
}
This is a string


As you may see in the previous example, strings can be initialized with any valid string literal just like numerical type variables can be initialized to any valid numerical literal. Both initialization formats are valid with strings:

1
2
string mystring = "This is a string";
string mystring ("This is a string");


Strings can also perform all the other basic operations that fundamental data types can, like being declared without an initial value and being assigned values during execution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// my first string
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string mystring;
  mystring = "This is the initial string content";
  cout << mystring << endl;
  mystring = "This is a different string content";
  cout << mystring << endl;
  return 0;
}
This is the initial string content
This is a different string content

class

std::string

<string>
typedef basic_string<char> string;
String class
Strings are objects that represent sequences of characters.

The standard string class provides support for such objects with an interface similar to that of standard containers, but adding features specifically designed to operate with strings of characters.

The string class is an instantiation of the basic_string class template that uses char as the character type, with its default char_traits and allocator types (see basic_string for more info on the template).

Member types

member type definition
value_type char
traits_type char_traits<char>
allocator_type allocator<char>
reference char&
const_reference const char&
pointer char*
const_pointer const char*
iterator a random access iterator to char (convertible to const_iterator)
const_iterator a random access iterator to const char
reverse_iterator reverse_iterator<iterator>
const_reverse_iterator reverse_iterator<const_iterator>
difference_type ptrdiff_t
size_type size_t

Member functions

(constructor)
Construct string object (public member function )
(destructor)
String destructor (public member function )
operator=
String assignment (public member function )

Iterators:
begin
Return iterator to beginning (public member function )
end
Return iterator to end (public member function )
rbegin
Return reverse iterator to reverse beginning (public member function )
rend
Return reverse iterator to reverse end (public member function )
cbegin
Return const_iterator to beginning (public member function )
cend
Return const_iterator to end (public member function )
crbegin
Return const_reverse_iterator to reverse beginning (public member function )
crend
Return const_reverse_iterator to reverse end (public member function )

Capacity:
size
Return length of string (public member function )
length
Return length of string (public member function )
max_size
Return maximum size of string (public member function )
resize
Resize string (public member function )
capacity
Return size of allocated storage (public member function )
reserve
Request a change in capacity (public member function )
clear
Clear string (public member function )
empty
Test if string is empty (public member function )
shrink_to_fit
Shrink to fit (public member function )

Element access:
operator[]
Get character of string (public member function )
at
Get character in string (public member function )
back
Access last character (public member function )
front
Access first character (public member function )

Modifiers:
operator+=
Append to string (public member function )
append
Append to string (public member function )
push_back
Append character to string (public member function )
assign
Assign content to string (public member function )
insert
Insert into string (public member function )
erase
Erase characters from string (public member function )
replace
Replace portion of string (public member function )
swap
Swap string values (public member function )
pop_back
Delete last character (public member function )

String operations:
c_str
Get C string equivalent (public member function )
data
Get string data (public member function )
get_allocator
Get allocator (public member function )
copy
Copy sequence of characters from string (public member function )
find
Find content in string (public member function )
rfind
Find last occurrence of content in string (public member function )
find_first_of
Find character in string (public member function )
find_last_of
Find character in string from the end (public member function )
find_first_not_of
Find absence of character in string (public member function )
find_last_not_of
Find non-matching character in string from the end (public member function )
substr
Generate substring (public member function )
compare
Compare strings (public member function )

Member constants

npos
Maximum value for size_t (public static member constant )

Non-member function overloads

operator+
Concatenate strings (function )
relational operators
Relational operators for string (function )
swap
Exchanges the values of two strings (function )
operator>>
Extract string from stream (function )
operator<<
Insert string into stream (function )
getline
Get line from stream into string (function )
分享到:
评论

相关推荐

    Prentice.Hall.C++.for.Business.Programming.2nd.Edition.2005.chm

    Other Integer Data Types 36 Chapter Review 42 Chapter 2. Real Numbers 45 Section 2.1. Real Numbers 45 Section 2.2. Solving Problems with Real Numbers 52 Section 2.3. More on Arithmetic 64 ...

    C++.Programming.From.Problem.Analysis.to.Program.Design.7th.Edition

    Namespaces, the class string, and User-Defined Simple Data Types. Chapter 8. Arrays. Chapter 9. Records (structs). Chapter 10. Classes and Data Abstraction. Chapter 11. Inheritance and Composition. ...

    Google C++ International Standard.pdf

    4.7 Multi-threaded executions and data races . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 4.8 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

    C++超详细的基础教程

    Variables and Data types 3.常量 Constants 4.操作符/运算符 Operators 5.控制台交互 Communication through console 3.控制结构和函数 Control structures and Functions 1.控制结构 Control Structures 2....

    c++ 2008

    Chapter 7: Defining Your Own Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . 331 Chapter 8: More on Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 ...

    Wrox - Ivor Horton's Beginning Visual C++ 2010 Apr 2010

    CHAPTER 7 Defi ning Your Own Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 CHAPTER 8 More on Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

    Debugging with GDB --2007年

    Table of Contents Summary of GDB . . . . . . . . ....Free software ....Contributors to GDB ....A Sample GDB Session ....Loading the Executable ....Setting Display width....Setting Breakpoints ....Running the executable ...

    Springer.The.Developer’s.Guide.to.Debugging.2008.pdf

    3.7 Learn to Inspect Data: Variables and Expressions . . . . 29 3.8 A Debug Session on a Simple Example . . . . . . 30 4 Fixing Memory Problems . . . . . . . . . . . . 33 4.1 Memory Management in C/...

    C++ 标准 ISO 14882-2011

    1.10 Multi-threaded executions and data races . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.11 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

    最新版的DebuggingWithGDB7.05-2010

    Table of Contents Summary of gdb . . . . . . . . ....Free Software ....Free Software Needs Free Documentation ....Contributors to gdb....1 A Sample gdb Session ....2 Getting In and Out of gdb ....2.1 Invoking gdb ....

    C++基础教程完整版

    Variables and Data types 3. 常量 Constants 4. 操作符/运算符 Operators 5. 控制台交互 Communication through console 3. 控制结构和函数 Control structures and Functions 1. 控制结构 Control ...

    Go Programming

    3.4 Some Basic Data Types .............................................. 57 3.4.1 Numeric Data Types ............................................ 57 3.4.2 Character Data Type ............................

    Debugging with GDB --2003年6.0

    Examining Data . . . . . . . . . . . . . . . . . . . . . . . . . . 65 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 8.10 8.11 8.12 8.13 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

    DebuggingWithGDB 6.8-2008

    Table of Contents Summary of gdb . . . . . . . . ....Free Software ....Free Software Needs Free Documentation ....Contributors to gdb....1 A Sample gdb Session ....2 Getting In and Out of gdb ....2.1 Invoking gdb ....

    The way to go

    Chapter 4—Basic constructs and elementary data types.......................................................49 4.1. Filenames—Keywords—Identifiers......................................................

    [Go语言入门(含源码)] The Way to Go (with source code)

    Chapter 4—Basic constructs and elementary data types.......................................................49 4.1. Filenames—Keywords—Identifiers......................................................

    Practical C++ Programming C++编程实践

    Arrays, Qualifiers, and Reading Numbers Arrays Strings Reading Data Initializing Variables Multidimensional Arrays C-Style Strings Types of Integers Types of Floats Constant and Reference ...

    Tricks of the Windows video Game Programming---part1

    Tricks of the Windows video Game Programming &lt;br&gt;PART I Windows ...Types of Games ....................................................................................13 Brainstorming.................

    The.Go.Programming.Language.0134190440.epub

    Early chapters cover the structural elements of Go programs: syntax, control flow, data types, and the organization of a program into packages, files, and functions. The examples illustrate many ...

    Learn.Cplusplus.In.A.DAY.1519318588.epub

    Chapter 3: Variables and Data Types Chapter 4: Operators Chapter 5: Advanced Data Types Chapter 6: Loops and Conditional Statements Chapter 7: Arrays and Pointers Chapter 8: Functions Chapter 9: ...

Global site tag (gtag.js) - Google Analytics