You are on page 1of 35

C++ Data Types and Basic IOs

HJ Chen
2017/10/16
References
> Ivor Horton/ Beginning Visual C++ 2013, 2014 Ed.
> Bjarne Stroustrup/ The C++ Programming Language, 4th Ed., 2013
> Bjarne Stroustrup/ The Design and Evolution of C++, 1994
> Bjarne Stroustrup Website http://www.stroustrup.com/
> Deitel & Deitel/ C++ How To Program, 2nd Ed., 1998
> Juan Soulié/ C++ Language Tutorial, cplusplus.com, 2007
> C++ Website http://www.cplusplus.com/
> C++ Programming / Wikibooks.org, 2012
> C Programming / Wikibooks.org, 2012
> More C++ Idioms/Print Version

2
Basic Concepts
Basic Concepts
 Basic Structure of C++ Program  The const Modifier
 Program Example  Operator Precedence
 A Simple Program Structure  Rules for Casting Operands
 Header Files, Namespaces and the Using  Explicit Casts
Declaration  The auto Keyword
 Sizes of Fundamental Data Types  The Bitwise Operators
 Ranges of C++ Fundamental Data Types  Bitwise Shift Operators
 Literals  Storage Duration and Scope
 Scope
 ISO C++ (C++98) Keywords
 Automatic and Static Variables
 Defining Synonyms for Data Types
 Old Style of Enumerations
 Basic Input/Output Operations
 Type-safe Enumerations
 Escape Sequences
 Assignment Statement, Lvalues and
Rvalues
4
Basic Structure of C++ Program
> Header Files
– Standard Library Functions, Standard Classes, Standard Template Library and Namespace
– Application Program Interfaces (API), and 3rd Party Libraries
– User Defined Symbols, Functions, Libraries and User Defined Data Types
> Application Entry Functions
– main, _tmain, WinMain, CWinObj, DllMain, etc.
> Application Variables, Functions and Objects
> Inside Function
– Variables
– Objects
– Control Structures
• if, if-else, switch-case
• for, while, do-while
• break, continue, return
> Comments
– /* */, //
5
A Simple Program Structure

6
Data Source: Ivor Horton
C Program Example
Comment

Include header files

Function definition

return control

main function

Variables

Message outputs and variable inputs

Control structure
Invoke function
return control

7
C++ Program Example

8
Header Files, Namespaces and the Using Declaration
> The standard library is an extensive set of routines that carry out many common tasks, such as
dealing with input and output and performing basic mathematical calculations.
> An #include directive is one of several preprocessor directives.
#include <iostream>
> A namespace is a mechanism for minimizing the risk of inadvertently using duplicate names. It
does this by associating a given set of names, such as those from the standard library, with a
sort of family name, which is the namespace name.
> The two colons that separate the namespace name from the entity name form an operator
called the scope resolution operator.
using std::cout; // by individual class or object
Or
using namespace std; // full set
> These are using declarations. They tell the compiler that you intend to use the names cout and
endl from the namespace std without specifying the namespace name.

9
Data Source: Ivor Horton
Sizes of Fundamental Data Types

Data Source: https://msdn.microsoft.com/en-


us/library/cc953fe1.aspx

10 Data Source: http://en.cppreference.com/w/cpp/language/types


Ranges of C++ Fundamental Data Types

11
Data Source: Ivor Horton
Literals

12
Data Source: Ivor Horton
Alternative Tokens

13 Data Source: ISO Standard for Programming Language C++ (Working Draft, n4687, 2017/07/30)
C++ Keywords (1)

14
Data Source: Bjarne Stroustrup/ The C++ Programming Language
C++ Keywords (2)
Keywords

Alternative
Representations

15 Data Source: ISO Standard for Programming Language C++ (Working Draft, n4687, 2017/07/30)
Defining Synonyms for Data Types

16
Data Source: Ivor Horton
Basic Input/Output Operations
#include <stdio.h>
#include <iostream>
using namespace std;

Input:
int num1 = 0, num2 = 0;
double factor = 0.0;

scanf("%d %f %d", &num1, &factor, &num2);or


cin >> num1 >> factor >> num2;

Output:
printf("%d %f %d\n", num1, factor, num2);
or
cout << num1 << " " << factor << " " << num2 << endl;

17
Data Source: Ivor Horton
Escape Sequences

Data Source: Ivor Horton

18 Data Source: ISO Standard for Programming Language C++ (Working Draft, n4687, 2017/07/30)
Assignment Statement, Lvalues and Rvalues
The assignment statement enables you to calculate the value of an expression which appears
on the right hand side of the equals sign, and store the result in the variable specified on the left
hand side.
An lvalue is something that refers to an address in memory and is so called because any
expression that results in an lvalue can appear on the left of the equals sign in an assignment
statement.
Most variables are lvalues, because they specify a place in memory.
There are variables that aren’t lvalues and can’t appear on the left of an assignment because
their values have been defined as constant.

Example:
int a = 5, b = 10;
a = a + b;

a and b are lvalues.


The expression a + b is not an lvalue is reffered to as an rvalue.
19
Data Source: Ivor Horton
The const Modifier
const double pi = 3.1415963;
const is a type modifier that indicates that the variable pi is not just of type double but is also a
constant.
A variable declared as const is not an lvalue and, therefore, can’t legally be placed on the left
of an assignment operation.

20
Data Source: Ivor Horton
Operator Precedence

Operator precedence orders the


operators in a priority sequence.

In any expression, operators with the


highest precedence are always
executed first, followed by operators
with the next highest precedence, and
so on, down to those with the lowest
precedence of all.

Data Source: http://www.cplusplus.com/

21
Rules for Casting Operands
1. Converting in the rank from high to low (from a to i)
a. long double b. double c. float d. unsigned long long e. long long f. unsigned
long g. long h. unsigned int i. int
2. If either operand is of type long double, the other is converted to long double.
3. If either operand is of type double, the other is converted to double.
4. If either operand is of type float, the other is converted to float.
5. Any operand of type char, signed char, unsigned char, short, or unsigned short is
converted to type int.
6. An enumeration type is converted to the first of int, unsigned int, long, or unsigned long
that accommodates the range of the enumerators.
7. If either operand is of type unsigned long, the other is converted to unsigned long.
8. If one operand is of type long and the other is of type unsigned int, then both operands
are converted to type unsigned long.
9. If either operand is of type long, the other is converted to type long.
22
Data Source: Ivor Horton
Explicit Casts
With mixed expressions involving the basic types, your compiler automatically arranges casting where
necessary, but you can also force a conversion from one type to another by using an explicit cast.
To cast the value of an expression to a given type, you write the cast in the form:
static_cast<the_type_to_convert_to>(expression)
The keyword static_cast reflects the fact that the cast is checked statically—that is, when your program is
compiled.
The difference between dynamic_cast and static_cast is that the dynamic_cast operator checks the
validity of a cast at run-time whereas the static_cast operator does not.
If a dynamic_cast operation is not valid, the result is null.
dynamic_cast can only be used with pointers and references to classes (or with void*). Its purpose is to
ensure that the result of the type conversion points to a valid complete object of the destination pointer type.
reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The
operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are
allowed: neither the content pointed nor the pointer type itself is checked.
const_cast manipulates the constness of the object pointed by a pointer, either to be set or to be
removed.

23 Data Source: Ivor Horton and http://www.cplusplus.com/


The auto Keyword
> You can use the auto keyword as the type of a variable in a definition statement and have its type
deduced from the initial value you supply.
auto n = 16; // Type is int
auto pi = 3.14159; // Type is double
auto x = 3.5f; // Type is float
auto found = false; // Type is bool
> In each of these cases, the type assigned to the variable you are defining is the same as that of
the literal used as the initializer. Of course, when you use the auto keyword in this way, you must
supply an initial value for the variable.
> Suppose you write:
auto n {16};
> The compiler will not deduce the type from the items in the list, but from the list itself. The type
assigned to n will not be int, but will be std::initializer_list<int>, which is the type of this particular
initializer list.
auto n(16); // Type is int
const auto e = 2.71828L; // Type is const long double
const auto dozen(12); // Type is const int
24 auto factor(n*pi*pi); // Type is double Data Source: Ivor Horton
The Bitwise Operators
> There are six bitwise operators:
& bitwise AND | bitwise OR ^ bitwise exclusive OR
~ bitwise NOT >> shift right << shift left

25
Data Source: Ivor Horton
Bitwise Shift Operators

26
Data Source: Ivor Horton
Storage Duration and Scope

27
Data Source: Ivor Horton
Scope
 Local scope: A name declared in a function or lambda is called a local name. Its scope extends
from its point of declaration to the end of the block in which its declaration occurs. A block is a
section of code delimited by a {} pair.
 Class scope: A name is called a member name (or a class member name) if it is defined in a class
outside any function, class, enum class, or other namespace. Its scope extends from the opening
{ of the class declaration to the end of the class declaration.
 Namespace scope: A name is called a namespace member name if it is defined in a namespace
outside any function, lambda, class, enum class, or other namespace. Its scope extends from the
point of declaration to the end of its namespace.
 Global scope: A name is called a global name if it is defined outside any function, class, enum
class, or namespace. The scope of a global name extends from the point of declaration to the end
of the file in which its declaration occurs.
 Statement scope: A name is in a statement scope if it is defined within the () part of a for-, while-,
if-, or switch-statement. Its scope extends from its point of declaration to the end of its statement.
All names in statement scope are local names.
 Function scope: A label is in scope from its point of declaration until the end of the function.
28
Data Source: Bjarne Stroustrup/ The C++ Programming Language
Automatic and Static Variables
> An automatic variable is “in scope” from the point at which it is declared until the end of the block
containing its declaration. The space that an automatic variable occupies is allocated in a
memory area.
> An automatic variable is created when it is defined and space for it is allocated on the stack; it
automatically ceases to exist at the end of the block containing its definition.
> Variables declared outside of all blocks and classes (I will discuss classes later in the book) are
called globals and have global scope, which is also called global namespace scope or file scope.
> Globals have static storage duration by default. Static storage duration means they exist from the
start of execution of a program until the program ends.
> A static variable continues to exist for the life of a program even though it is declared within a
block and available only from within that block (or its sub-blocks). It still has block scope, but it
has static storage duration.
> If you don’t provide an initial value for a static variable, it will be initialized with 0 converted to the
type applicable to the variable.

29
Data Source: Ivor Horton
Old Style of Enumerations
Case 1:
enum Week { Mon, Tues, Wed, Thurs, Fri, Sat, Sun } weekDay;
The value of first member is 0 by default.

weekDay = Thurs; In this case, the value of weekDay is 3.

Case 2:
enum Week { Mon = 1, Tues, Wed, Thurs, Fri, Sat, Sun = 0 } weekDay;
The value of first member is 1 by setting. The value of last member is 0 by setting.

weekDay = Thurs; In this case, the value of weekDay is 4.

Case 3:
enum Punctuation {Comma = ',', Exclamation = '!', Question = '?'} things;

30
Data Source: Ivor Horton
Type-safe Enumerations
> C++ 11 introduced a new form of enumeration. These enumerations are said to be type-
safe because implicit conversion of enumerator values to another type will not occur. You
use the class keyword following enum to specify the new enumeration type.
enum class Suit {Clubs, Diamonds, Hearts, Spades};
Suit suit {Suit::Diamonds};
enum class Jewels {Diamonds, Emeralds, Opals, Rubies, Sapphires};
> There are no name conflicts because the enumerator names are not exported into the
enclosing scope. You must always qualify the enumerator names with the type name so
Suit::Diamonds is always distinct from Jewels::Diamonds.
int suitValue {static_cast<int>(suit)}; // Convert suit to int
> The enumerator values are type int by default, but you can change this:
enum class Jewels : char {Diamonds, Emeralds, Opals, Rubies, Sapphires};

31
Data Source: Ivor Horton
Exercises
Exercise 2-1
> Define an integer as a local variable and using scanf and printf functions to do the input and
output control, ask user to enter a positive integer, do an incremental summation from 1 up to
the entered positive value, and then print out the final summation value. Design the other
program by using cin and cout to do the same processes.

33
Exercise 2-2
> Similar to pages 7 and 8 to design the conversion programs from Celsius to Fahrenheit
with the basic input/output controls of both C style and C++ style.

34

You might also like