Professional Documents
Culture Documents
Chapter 3
Chapter 3
C++ Basics
1
Outline
• Fundamental components of C++
• Basic Elements of C++
• Data Types, Variables, and Constants
• Operators
• Precedence of Operators
• Simple Type Conversion
• Statements
2.1.5 Structure of C++ Program
• [Comments]
• [Preprocessor directives]
• [Global variable declarations]
• [Prototypes of functions]
• [Definitions of functions]
2.2 Fundamental components of C++
• A C++ program is a collection of one or more subprograms,
called functions
• A subprogram or a function is a collection of statements
that, when activated (executed), accomplishes something
• Every C++ program has a function called main
• The smallest individual unit of a program written in any
language is called a token
• The hello world program is one of the simplest programs,
but it already contains the fundamental components that
every C++ program has.
2.2.1 First Program in C++
// A hello world program in C++
#include<iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
---// A hello world program in
C++
• The first line in our program is a comment line.
• Every line that starts with two slash signs ( // ) are
considered comments and will have no effect on the
behavior or outcome of the program.
• (Words between /* and */ will also be considered as
comments (old style comments)).
• Use comments in your programs to explain difficult
sections, but don’t overdo it.
• It is also common practice to start every program with a
brief description on what the program will do.
--- #include<iostream>
• Lines beginning with a pound sign (#) are used by
the compilers pre-processor.
• In this case the directive #include tells the pre-
processor to include the iostream standard file.
• This file iostream includes the declarations of the
basic standard input/output library in C++.
• (See it as including extra lines of code that add
functionality to your program).
--- using namespace std;
• All the elements of the standard C++ library are
declared within what is called a namespace.
• In this case the namespace with the name std.
• We put this line in to declare that we will make
use of the functionality offered in the namespace
std.
• This line of code is used very frequent in C++
programs that use the standard library.
• You will see that we will make use of it in most of
the source code included in these tutorials.
--- int main()
• int is what is called the return value (in this case
of the type integer. Integer is a whole number).
• Every program must have a main() function.
• The main function is the point where all C++
programs start their execution.
• The word main is followed by a pair of round
brackets.
• That is because it is a function declaration. It is
possible to enclose a list of parameters within the
round brackets.
---cont
• A C++ program is a collection of one or
more subprograms (functions)
• Function
– Collection of statements
– Statements accomplish a task
• Every C++ program has a function called
main
--- {}
• The two curly brackets (one in the beginning and
one at the end) are used to indicate the beginning
and the end of the function main. (Also called the
body of a function).
• Everything contained within these curly brackets
is what the function does when it is called and
executed.
--- cout << “Hello World”;
• This line is a C++ statement.
• A statement is a simple expression that can produce
an effect.
• In this case the statement will print something to our
screen.
• cout represents the standard output stream in C++.
• In this a sequence of characters (Hello World) will be
send to the standard output stream.
• The words Hello World have to be between ” “, but
the ” ” will not be printed on the screen. They indicate
that the sentence begins and where it will end.
---cont
• cout is declared in the iostream standard file within the std
namespace. This is the reason why we needed to include
that specific file. This is also the reason why we had to
declare this specific namespace.
• As you can see the statement ends with a semicolon (;).
• The semicolon is used to mark the end of the statement.
• The semicolon must be placed behind all statements in C+
+ programs.
• So, remember this. One of the common errors is to forget
to include a semicolon after a statement.
--- return 0;
• The return statement causes the main function
to finish.
• You may return a return code (in this case a zero)
but it depends on how you start your function
main( ).
• We said that main ( ) will return an int (integer).
• So we have to return something (in this case a
zero).
• A zero normally indicates that everything went ok
and a one normally indicates that something has
gone wrong
--- Indentations
• As you can see the cout and the return statement
have been indented or moved to the right side.
• This is done to make the code more readable. In a
program as Hello World, it seems a stupid thing to do.
• But as the programs become more complex, you will
see that it makes the code more readable.
• So, always use indentations and comments to make
the code more readable.
• It will make your life (programming life at least) much
easier if the code becomes more complex.
Example Structure
2.3 Basic Elements
• Five kind of tokens in C++
– Keywords (reserved words)
– Identifiers
– Literals
– Operators
– Comments
2.3.1 Keywords (reserved words)
• Words with special meaning to the compiler
• Have a predefined meaning that can’t be changed
• All reserved words are in lower-case letters
• Must not be used for any other purposes
2.3.2 Identifiers
• An identifier is name associated with a function or data
object and used to refer to that function or data object.
• Programmer given names
• Identify classes, variables, functions, etc.
• Consist of letters, digits, and the underscore character (_)
• Must begin with a letter or underscore
• Not be a reserved word
• C++ is case sensitive
• Some predefined identifiers are cout and cin
• Unlike reserved words, predefined identifiers may be
redefined, but it is not a good idea
--- valid and invalid Identifiers
2.3.3 Literals
• Literals are constant values which can be a number, a
character of a string.
• Explicit (constant) value that is used by a program
• Literals can be digits, letters or others that represent
constant value to be stored in variables
– Assigned to variables
– Used in expressions
– Passed to methods
• E.g.
– Pi = 3.14; // Assigned to variables
– C= a * 60; // Used in expressions
2.3.4 Comments
• Remark about programs
• Explain programs to other programmers
– Improve program readability
• Ignored by compiler
• Two types
– Single-line comment
• Begin with //
• Example
– // This is a text-printing program.
– Multi-line comment
• Start with /*
• End with */
• Typical uses
– Identify program and who wrote it
– Record when program was written
–
Example
1 /* Fig. 2.1: fig02_01.cpp
2 Text-printing program. */
3 #include <iostream> // allows program to output data to the screen
4
5 // function main begins program execution
6 int main()
7 {
8 cout << "Welcome to C++!\n"; // display message
9
10 return 0; // indicate that program ended successfully
11
Welcome to C++!
Good Programming Practice 2.1
– Pointers
2.5.1 Simple Data Types
• Three categories of simple data
int) 2,147,483,647
int
2 bytes -32,768 to 32,767
• Examples
20 - 4 / 5 * 2 + 3 * 5 %
4
(4 / 5)
((4 / 5) * 2)
((4 / 5) * 2) (3 * 5)
((4 / 5) * 2) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) + ((3 * 5) % 4)
2.6.2 Assignment Operator
• The assignment operator is used for storing a value
at some memory location (typically denoted by a
variable).
• Assignment operators are used to store the result of
mathematical operation in one of the operand which
is at left side of the operator.
• Assignment operator =
– Assigns value on left to variable on right
– Binary operator (two operands)
– Example:
• int a= 5;
• float b= 9.66;
• char ch=‘d’;
• int m, n, p;
• m = n = p = 100;
Examples
2.6.3 Relational Operators
• In order to evaluate a comparison between two
expressions, we can use the relational operator.
• (==, !=, > , <, >=, <=).
• The result of a relational operator is a bool value that can
only be true or false according to the result of the
comparison.
• E.g.: (7 = = 5) would return false or returns 0 (5 > 4)
would return true or returns 1
• The operands of a relational operator must evaluate to a
number.
• Characters are valid operands since they are represented by
numeric values.
• For E.g.: ‘A’ < ‘F’ would return true or 1. it is like (65 <
70)
--- cont
Operator
Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
Relational operators
2.6.4 Logical Operators(!, &&, ||)
• Like the relational operators, logical operators evaluate to 1 or 0.
– Logical negation (!) is a unary operator, which negates the logical value of its operand. If its operand is non
zero, it produce 0, and if it is 0 it produce 1.
– Logical AND (&&) produces 0 if one or both of its operands evaluate to 0 otherwise it produces 1.
– Logical OR (||) produces 0 if both of its operands evaluate to 0 otherwise, it produces 1.
--- con
2.6.5 Increment/Decrement
Operators: (++) and (--)
• The auto increment (++) and auto decrement (--)
operators provide a convenient way of,
respectively, adding and subtracting 1 from a
numeric variable.
• E.g.: if a was 10 and if a++ is executed then a will
automatically changed to 11.
• Increment operator: increment variable by 1
• Decrement operator: decrement variable by 1
Prefix and Postfix:
• The prefix type is written before the variable.
– Eg (++ myAge), whereas the postfix type appears after
the variable name (myAge ++).