Top Banner
8/22/2019 3 Syntax Rules http://slidepdf.com/reader/full/3-syntax-rules 1/41 Dr. Siti Barirah Ahmad Anas [email protected] 03-89466439 Room A.04.89 C++ Syntax Rules
41

3 Syntax Rules

Aug 08, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 1/41

Dr. Siti Barirah Ahmad Anas

[email protected]

Room A.04.89

C++ Syntax Rules

Page 2: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 2/41

• C++ Program Structure – Keywords – Identifiers – Constant – ASCII Code – Character sets – Standard data types – Variable – Operators – Punctuators

• FormattedInput/Output

• Expression – Unary Expression

 – Assignment Expression – Programming Examples

• Typedef and sizeofoperator 

• Arithmetic conversion• Statement

Page 3: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 3/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• The rules of a programming language are called itssyntax

• Misusing the language is called a syntax error. Thecompiler will alert you to any syntax errors, all of whichmust be corrected

• If you speak the language perfectly, but your instructionsdon't generate the correct answer. This is called asemantic error 

• Runtime error is when there occurs an expression which is

impossible to compute such as divide by 0 error 

Page 4: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 4/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• A C++ program – Contains preprocessor directives that tells it how to

prepare program for compilation, e.g. #include

 – Made of a global declaration sections with one or more functions

 – Only one function should be named as main

 – All functions are divided into 2 sections:• Definition section

 – describe data to be used within the function – Local definition

• Statement section – Follows definition section – Contains set of instructions, called statement

Page 5: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 5/41

Preprocessor directives

Global declarations

int main (void){

}

Local definitions

Statements

#include <iostream.h>

int a=1,b=2;

int main (void){

} // main

int c;

c=a+b;

return 0;

Example

Page 6: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 6/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• A C++ program is first constructed as a sequence of characterssuch as:

 – uppercase letters => A to Z

 – lowercase letters => a to z

 – digits => 0 to 9

 – special characters => + - * / = ( ) { } [ ]< > „ “ ! # % & _ | ^ ~ \ . , ; : ?

 – white space character => blank, newline, tab

• These characters are collected by compiler into syntactic unitscalled tokens which are: keywords, identifiers, constant,operators and punctuators.

Page 7: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 7/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

Keywords common to the C and C++ programming languages

auto break case char constcontinue default do double else

enum extern float for goto

if int long register return

short signed sizeof static struct

switch typedef union unsigned void

volatile whileC++-only keywords

and and_eq asm bitand bitor  

bool catch class compl const_cast

delete dynamic_cast explicit export false

friend inline mutable namespace new

not not_eq operator or or_eq

private protected public reinterpret_cast static_cast

template this throw true try

typeid typename using virtual wchar_t

xor xor_eq

Page 8: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 8/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Composed of a sequence of letters, digits andunderscore (_)

• The first character of identifier cannot be a digit• Case sensitive• Is a valid variable name

Valid Not validm not#meid 102_southidentifier2 -minus

Page 9: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 9/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• C++ manipulates various kinds of values.

• Basic types of constant consists of:

a) integer constant  –  integer valued number

• integer can be written in three different number system:

 – decimal, octal or hexadecimal• range: -32768 to 32767

 – decimal digits taken from set of 0 through 9eg: 0, 17, 9999

 – octal digits taken from set of 0 through 7,however, first digit must be 0, eg: 0, 01, 0743,077777

 – hexadecimalmust begin with 0x or 0Xfollowed by any combinations of digits 0through 9 and letters a through f (or A throughF ), eg: 0x, 0x1, 0x7FFF , 0xabcd

Page 10: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 10/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

(b) floating point constant• base-10 number that contains either a decimal point or exponent (or 

both)

• range: 3.4E-38 - 3.4E+38

• eg: 1.0, 3.1415, 0. , 1. , 2E-8, 1.6667E+8, 0.006e-3

(c) character constant• is a single character enclosed in single quotation marks• eg: „i‟, „z‟, „3‟, „?‟

• there are several character constant that expressed in terms of escapesequence eg: „\n‟, „\t‟, „\\‟, „\‟‟, „\”‟, „\‟

Page 11: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 11/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

(d) string constant• a sequence of characters enclosed in double quotation marks• eg:

“abc”, “ ”, “Line 1\nLine 2\nLine 3”, “”

• string constants are stored by the compiler as arrays of characters

• 2 string constants separated only by white space are combined into onestring

• eg:

“abc” “def” = “abcdef”

(e) enumeration (enum)

• user defined constants

• eg:

enum day {sun, mon, tue, wed}

Page 12: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 12/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Character from the character constantcomes from character set, supplied byhardware manufacturer 

• ASCII – American Standard Code for Information

Interchange

 – used by most computers

• EBCIDIC – Extended Binary Coded Decimal Interchange

Code

 – used only by IBM Mainframes and their clones

Page 13: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 13/41

Table 1:

ASCII Code

Page 14: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 14/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

Written in C Name of character Integer value‘\a’ Alert 7

‘\\’ Backslash 92

‘\b’ Backspace 8

‘\r’ Carriage return 13

‘\”’ Double quote 34

‘\f’ Form feed 12

‘\t’ Horizontal tab 9

‘\n’  Newline 10

‘\0’  Null character 0

‘\’’ Single quote 39

‘\v’ Vertical tab 11

Page 15: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 15/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Defines a set of values and a set of operationsthat can be applied on those values

• Standard/fundamental data types – char, int, double

• Derived types

 – Pointer, enumerated type, union, array etc.

Page 16: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 16/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• What is… – Named memory locations – Have a type and size

• Declarations

 – Used to name an object – E.g. char c;

• Definitions – Used to create an object

 – E.g. char c = „a‟;

• Normally, declarations and definitions aredone at the same time

Page 17: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 17/41

char code;

int i;

long national_debt;

float payRate;

double pi;

code

i

national_debt

payRate

pi

B

14

100000000000000

14.25

3.1415926536

Variable‟sIdentifier 

Variable‟stype

Variable‟sIdentifier 

program memory

Variables in Memory

Page 18: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 18/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Initializer establishes the first value that thevariable will contain

• Example:int count = 0;

int count, sum = 0;

int count = 0, sum = 0;

int count = 0,

int sum = 0;

• When a variable is defined, it is not initialized,

the programmer must initialize the variable

Page 19: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 19/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Arithmetic operators:

+ addition- subtraction* multiplication/ division% modulus

• Equality operators:

= = is equal!= not equal

• Relational operators:> greater than< less than

>= greater than or equal<= less than or equal

• punctuators: ( ) {} , ;

• parentheses immediately following main are not punctuator 

Page 20: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 20/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Operators have rules of  precedence andassociativity that determine precisely howexpressions are evaluated.

• Precedence and associativity describe the order 

in which each operator is evaluated by thecompiler.

• Precedence - -> determines the priority ofevaluation

• Associativity - -> determines the order in whichtwo or more operands with the same precedencewill be evaluated

Page 21: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 21/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• 1 + 2 * 3

» the value is 7

» * has higher precedence than +, causing themultiplication to be performed first, thenaddition.

• (1 + 2) * 3

» the value is 9» expressions inside parentheses are evaluated

first.

• 1 + 2 – 3 + 4 – 5

» The value is -1

» binary operators – and + have the sameprecedence, then use associativity rule “left toright”

• Refer table 2.

Table 2: Operator Precedence and Associativity

Page 22: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 22/41

Table 2: Operator Precedence and Associativity

Operator Type Operator Execution Order

Primary Expression Operators () [] . -> expr ++ expr -- left-to-right

Unary Operators* & + - ! ~ ++expr --expr (typecast)

sizeof()right-to-left

Binary Operators

* / %

left-to-right

+ -

>> <<

< > <= >=

== !=

&

^

|

&&

||

Ternary Operator ?: right-to-left

Assignment Operators = += -= *= /= %= >>= <<= &= ̂ = != right-to-left

Comma , left-to-right

Page 23: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 23/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Standard input file: keyboard• Standard output file: monitor 

• Information from input and to output file will bebuffered in a storage area

Keyboard

Monitor 

cin >>

cout <<

Memory

Buffer 

Page 24: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 24/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Purpose: display message on the monitor screen

• Syntax

cout >> “…” >> variable1 >> 

• Examples

cout >> “Hello World!\n”

cout >> “The average value is” >> ave >> “\n”

Page 25: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 25/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Output field can be set• Using #include <iomanip> 

• Exampledouble x = 34.95;

cout << setw(8);

cout << setprecision(2);

cout << setprecision(2) << setw(8) << x;

• Output###34.95

Page 26: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 26/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Purpose: read value from one/more variablesfrom the input

• Syntax

cin >> variable1 >> variable2 >> variable3

• Examples

cin >> first

cin >> first >> middle >> last

Khamis pagi 5 ogos? Saya OK no problem. Same venue UNITEN…? Time..?barirah

Page 27: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 27/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Sequence of operands andoperators that reduces to a single

value e.g. 2 + 5• Expression type – primary, unary,

binary, etc.

• Precedence – determines the priority

Page 28: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 28/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Primary expressions

 – Identifier, constant and parentheticalexpression

 – E.g. a, 7 and (2 + a - 3)

• Binary expressions

 – Formed by operand-operator-operandcombination

 – E.g. additive : a + 7 and multiplicative: 6/ 2

Page 29: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 29/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Increment operator ++ and decrement operator --are unary operators with the same precedence asthe unary plus and minus, associate from right toleft.

• Occur in either prefix or postfix position, anddifferent effects may occur.

• ++i and i++ causes the stored value of i in memoryto be incremented by 1

• ++i increment i first then do expression (prefix)

• i++ do expression first then increment i (postfix)

Page 30: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 30/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• example:

int a, b, c = 0;

a=++c;

 b=c++;

cout >> a >> b >> ++c;

note: ++ and -- cause the value of a variable in

memory to be changed

Page 31: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 31/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Evaluates the operand on the right side of theoperator (=) and places the value in thevariable on the lefta = b + c;

• Assignment operators:= += -= /= %= >>= <<=

&= ?= |= – same precedence – right to left associativity

 – changed value of variable – Left operand must be a single value

Page 32: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 32/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Simple Assignment – As in algebraic expression

 – E.g. a = 5, b = x + 1, i = i + 1

• Compound assignment – Shorthand notation for a simple expression

 – E.g. x *= y equals to x = x * y

• Example – x *= y + 3 evaluated as x = x * (y + 3)

Page 33: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 33/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• E.g.1

int a, b = 2, c = 3;

a = b + c;

• E.g. 2a=b=c=0; equivalent to a=(b=(c=0));

k += 2; k=k+2;

j *= k + 3; j=j * (k+3);

Page 34: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 34/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

int a=3, b=4, c=5, x, y;

x = a * 4 + b / 2 - c * b;

y = --a * (3 + b) / 2 - c++ * b;

What is the new value of each variableafter executing the above expressions?

Page 35: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 35/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• allows programmer to associate a type withan identifier 

• eg: typedef char uppercase;

typedef int inches;

uppercase u;

inches length, width;

• uses:

 – have type names that reflect the intended use

     t    y    p    e      d    e      f

Page 36: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 36/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

    s      i    z    e

    o      f

• a unary operator to find the number of bytes needed to store an objectin memory.

• sizeof (object)• note: object can be a type,

expression, an array or structure type

• eg: sizeof (char) = 1

Page 37: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 37/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Used for mixed type expression – E.g. int + float

• 2 conversion types – Implicit type conversion

• Type is automatically converted by C++program

• Based on the promotion hierarchy

 – Explicit type conversion

• Uses cast expression operator e.g. (int) a

• Type is converted by the programmer 

Page 38: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 38/41

char 

short

int

Unsigned int

Long int

Unsigned long int

float

double

Long double

The Promotion Hierarchy

Page 39: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 39/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• A.k.a. casting

• Example

 – (float) a – (float) (x + y)

 – (float) (a / 10)

 – (float) a / 10

Page 40: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 40/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Causes an action to be performed inC++ program

• 6 types altogether but concentrate

on the first two: – Expression statement

• Expression ended with semicolon

 – Compound statement• Unit of code between the opening and

closing braces

Page 41: 3 Syntax Rules

8/22/2019 3 Syntax Rules

http://slidepdf.com/reader/full/3-syntax-rules 41/41

• Technology Oriented • Business Driven • Sustainable Development • Environmental Friendly

• Statements and defined constant – Common error:

#define PI 3.142;

...

area = PI*r*r;

 – Actual evaluation is

area = 3.142;*r*r;