C++ Simple Types

The simple types supported in C/C++ are

  • A Boolean type (bool)
  • Character types (char and wchar_t)
  • Integer types (short, int, long)
  • Floating point numbers (double, float, long double, etc.)
  • Pointers (int*, char*, bool*, double*, void*, etc.)

In addition, C and C++ both provide a name that signifies the absence of type information (void).

C++ simple types can (variously) be modified by the following keywords to produce other simple types:

  • short
  • long
  • signed
  • unsigned[11]

    [11] For a brief discussion of the differences between signed and unsigned integral types, see Section 19.4.

C++ compilers allow you to omit "int" from short int, long int, and unsigned int. You can omit signed from most types, since that is the default.

Since the range of values for a particular type depends on the underlying architecture of the machine on which the compiler is running, the ANSI/ISO standard for C++ does not specify the size (in bytes) of any of these types. It only guarantees that a given type (e.g., int) must not be smaller than one that appears above it (e.g., short) in Table 1.2.

Table 1.2. Simple Types Hierarchy

Byte/char types

Integral types

Floating point types

bool

short int

float

char

int

double

signed char

long int

long double

unsigned char

unsigned short

 

wchar_t

unsigned int

 
 

unsigned long

 

There is a special operator sizeof() that returns the number of chars[12] that a given expression requires for storage. Unlike most functions, the sizeof() operator can take value expressions or type expressions.

[12] On most systems, a single char is a byte.

Example 1.7 shows how sizeof() can be used, and some of the values it returns on a 32-bit x86 system.

Example 1.7. src/early-examples/size.cpp

#include 
#include 
#include 

int main(int argc, char* argv[]) {
 using namespace std;
 int i=0;
 char array1[34] = "This is a dreaded C array of char";
 char array2[] = "if not for main, we could avoid it entirely.";
 char *charp = array1; <-- 1
 string stlstring = "This is an Standard Library string. Much
 preferred." ;
 assert (sizeof(i) == sizeof(int));
 cout << "sizeof char = " << sizeof(char) << '
';
 cout << "sizeof wchar_t = " << sizeof(wchar_t) << '
';
 cout << "sizeof int = " << sizeof(int) << '
';
 cout << "sizeof long = " << sizeof(long) << '
';
 cout << "sizeof float = " << sizeof(float) << '
';
 cout << "sizeof double = " << sizeof(double) << '
';
 cout << "sizeof double* = " << sizeof(double*) << '
';
 cout << "sizeof array1 = " << sizeof(array1) << '
';
 cout << "sizeof array2 = " << sizeof(array2) << '
';
 cout << "sizeof stlstring = " << sizeof(stlstring) << endl;
 cout << "length of stlstring= " << stlstring.length() << endl;
 cout << "sizeof char* = " << sizeof(charp) << endl;
 return 0;
}

Output:


 sizeof char = 1
 sizeof wchar_t = 4
 sizeof int = 4
 sizeof long = 4
 sizeof float = 4
 sizeof double = 8
 sizeof double* = 4
 sizeof array1 = 34
 sizeof array2 = 46
 sizeof stlstring = 4
 length of stlstring = 38
 sizeof char* = 4
 

(1)pointer to first element of array

Notice that all pointers are the same size, regardless of their type. sizeof(stlstring) indicates it is only 4 bytes, but it is a complex class that uses dynamic memory, so we use length() to get the number of characters in the string.

The ranges of values for the integral types (bool, char, int) are defined in the standard header file limits.h. On a typical *nix installation that file can be found in a subdirectory of /usr/include.

1.8.1. main and Command Line Arguments

main() is a function (see Chapter 5), that is called at program startup. If the program accepts command line arguments, we must define main with its full parameter list.

C permits flexibility in the ways that arguments are defined in main(), so you may see it defined in a variety of ways:

int main(int argc, char* argv[])
int main(int argc, char ** argv)
int main(int argCount, char * const argValue[])

All of the above forms are valid, and each defines two parameters. These parameters contain enough information to reconstruct the command line arguments passed into the program from the parent process (a command line shell, a window manager, etc.).

Example 1.8 is a simple main program that prints its command line arguments. argValue, or argv for short, is a two-dimensional array (see Section 22.4) of char. argCount, or argc for short, is the number of char arrays in argv. argv contains each command line string as an item in its array.

Example 1.8. src/main/main1.cpp

#include 
using namespace std;
int main (int argCount, char* argValue[]) {
 for (int i=0; i


int main() "returns" an integer, which should be 0 if all went well, or a non-zero error code if something went wrong.

Try not to confuse this interpretation of 0 with the bool value false, which is equal to zero.

If we run this program and pass some arguments, we will see something like this in the output:

~/src/main> ./a.out foo bar "space wars" 123
argv# 0 is ./a.out
argv# 1 is foo
argv# 2 is bar
argv# 3 is space wars
argv# 4 is 123

The first argument is always the name of the executable. The other arguments are taken from the command line as strings separated by spaces or tabs. To pass a string that contains spaces as a single argument, you must enclose the string in quotes.

1.8.2. Arithmetic

Each programming language must provide facilities for doing basic arithmetic. For each of its native numerical types, C++ provides these four basic arithmetic operators:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)

These operator symbols are used to form expressions in the standard infix syntax that we learned in math class.

C++ provides shortcut operators that combine each of the basic operators with the assignment operator (=) so that, for example, it is possible to write

x += y;

instead of

x = x + y;

C++ also provides unary increment (++) and decrement (--) operators that can be used with integral types. If one of these operators is applied to a variable on the left (prefix), then the operation is performed before the rest of the expression is evaluated. If it is applied to a variable on the right (postfix), then the operation is performed after the rest of the expression is evaluated. Examples 1.9 through 1.13 demonstrate the use of the C++ arithmetic operators.

Example 1.9. src/arithmetic/arithmetic.cpp

[ . . . . ]
#include 

int main() {
 using namespace std;
 double x(1.23), y(4.56), z(7.89) ;
 int i(2), j(5), k(7);
 x += y ;
 z *= x ;
 cout << "x = " << x << "	z = " << z
 << "
x - z = " << x - z << endl ;

Integer division is handled as a special case. The result of dividing one int by another produces an int quotient and an int remainder. The operator / is used to obtain the quotient. The operator % (called the modulus operator) is used to obtain the remainder.

Example 1.10 shows the use of these integer arithmetic operators.

Example 1.10. src/arithmetic/arithmetic.cpp

[ . . . . ]


 cout << "k / i = " << k / i
 << "	k % j = " << k % j << endl ;
 cout << "i = " << i << "	j = " << j << "	k = " << k << endl;
 cout << "++k / i = " << ++k / i << endl;
 cout << "i = " << i << "	j = " << j << "	k = " << k << endl;
 cout << "i * j-- = " << i * j-- << endl;
 cout << "i = " << i << "	j = " << j << "	k = " << k << endl;

Mixed expressions, if valid, generally produce results that are of the widest of the argument types. We discuss this in more detail in Chapter 19.

Example 1.11 shows that the result of a double divided by an int is a double.

Example 1.11. src/arithmetic/arithmetic.cpp

[ . . . . ]

 cout << "z / j = " << z / j << endl ;

C++ also provides a full set of boolean operators to compare numeric expressions. Each of these operators returns a bool value of either false or true.

  • Less than (<)
  • Less than or equal to (<=)
  • Equal to (==)
  • Not equal to (!=)
  • Greater than (>)
  • Greater than or equal to (>=)

A bool expression can be negated with the unary not (!) operator. Two bool expressions can be combined with the operators

  • and (&&)
  • or (||)

We discuss bool expressions in more detail in Section 19.2.

Example 1.12. src/arithmetic/arithmetic.cpp

[ . . . . ]


 /* if() ... else approach */
 if(x * j <= z)
 cout << x * j << " <= " << z << endl ;
 else
 cout << x * j << " > " << z << endl;
 /* conditional operator approach */
 cout << x * k
 <<( (x * k < y * j) ? " < " : " >= ")
 << y * j << endl;
}

In addition to the binary boolean operators, Example 1.12 makes use of the conditional-expression.

The expression

(boolExpr) ? expr1 : expr2

returns expr1 if boolExpr is true, otherwise it returns expr2. Example 1.13 shows the output that this program produces.

Example 1.13. src/arithmetic/arithmetic.cpp

[ . . . . ]

Output:

x = 5.79 z = 45.6831
x - z = -39.8931
k / i = 3 k % j = 2
i = 2 j = 5 k = 7
++k / i = 4
i = 2 j = 5 k = 8
i * j-- = 10
i = 2 j = 4 k = 8
z / j = 11.4208
23.16 <= 45.6831
46.32 >= 18.24

Exercises: C++ Simple Types

1.

Here is an old favorite: Write a short program that asks the user to choose Celsius-to-Fahrenheit or Fahrenheit-to-Celsius. Then ask for a lower bound, an upper bound, and an increment. Using that information, produce an appropiate table with column headings. The main() part of your program should be relatively short. Most of the work should be performed by functions that you design, e.g., celsiusToFahrenheit(), fahrenheitToCelsius(), makeTable(), and so forth (with appropriate parameter lists).

2.

If you #include , you can make use of the random() function that generates a sequence of pseudo-random long ints in the range from 0 to RAND_MAX, which can be used in many interesting ways. It works by computing the next number in its sequence from the last number that it generated. The function srandom(unsigned int seed) sets its argument as the initializing value (seed) for the random sequence. Write a short program that tests this function by allowing the user to supply the seed from the keyboard and then generating a list of pseudo-random numbers.

3.

One trick is to use srandom(time(0)) to seed the random() function. Since time(0) returns the number of seconds since some initial starting point, the seed will be different each time you run the program. This allows you to write programs that have usefully unpredictable behavior patterns. Write a program that simulates a dice game that the user can play with the computer. Here are the rules to apply to your game:

  • The game is about repeated "throws" of a pair of dice.
  • Each die has six faces, which are numbered 1 through 6.
  • A throw results in a number that is the total of the two top faces.
  • The first throw establishes the player's number.
  • If that number is 7 or 11, the player automatically wins.
  • If that number is 2, the player automatically loses.
  • Otherwise, the player continues throwing until she wins (by matching her number) or loses (by throwing a 7 or an 11).
4.

Write a program that accepts two values from the user (customer): the total purchase amount and the amount submitted for payment.

Each of these values can be stored in a variable of type double. Then compute and display the change that will be given to the user. Express the change in terms of the number of $10 bills, $5 bills, $1 bills, quarters, dimes, nickels, and pennies. (Presumably, this output could be sent to a machine that dispenses those items automatically.)

For example, if the total purchase amount is $73.82 and the customer pays with a $100 bill, then the change should be: two $10 bills, one $5 bill, one $1 bill, no quarters, one dime, one nickel, and three pennies.

Convert the amount that is owed the customer to pennies, which can be stored as an int and then use the integer division operators.


Part I: Introduction to C++ and Qt 4

C++ Introduction

Classes

Introduction to Qt

Lists

Functions

Inheritance and Polymorphism

Part II: Higher-Level Programming

Libraries

Introduction to Design Patterns

QObject

Generics and Containers

Qt GUI Widgets

Concurrency

Validation and Regular Expressions

Parsing XML

Meta Objects, Properties, and Reflective Programming

More Design Patterns

Models and Views

Qt SQL Classes

Part III: C++ Language Reference

Types and Expressions

Scope and Storage Class

Statements and Control Structures

Memory Access

Chapter Summary

Inheritance in Detail

Miscellaneous Topics

Part IV: Programming Assignments

MP3 Jukebox Assignments

Part V: Appendices

MP3 Jukebox Assignments

Bibliography

MP3 Jukebox Assignments



An Introduction to Design Patterns in C++ with Qt 4
An Introduction to Design Patterns in C++ with Qt 4
ISBN: 0131879057
EAN: 2147483647
Year: 2004
Pages: 268

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net