0% found this document useful (0 votes)
28 views16 pages

Basic Elements of C

C++ tokens include special symbols, word symbols called keywords, and identifiers. Keywords are predefined words that have special meaning in C++ syntax and cannot be redefined, while identifiers can be defined and redefined. The document lists various C++ keywords, reserved words, literals, variables, constants, operators, and other basic elements of C++. It provides examples to explain the difference between keywords and identifiers.

Uploaded by

arpanabharani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views16 pages

Basic Elements of C

C++ tokens include special symbols, word symbols called keywords, and identifiers. Keywords are predefined words that have special meaning in C++ syntax and cannot be redefined, while identifiers can be defined and redefined. The document lists various C++ keywords, reserved words, literals, variables, constants, operators, and other basic elements of C++. It provides examples to explain the difference between keywords and identifiers.

Uploaded by

arpanabharani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 16

Basic Elements of C++ (I)

1.
Token
The smallest individual unit of a program written in any language is called a token. C++
tokens are divided into
special symbols, word symbols, and identifiers.
1)
Special Symbols
Special symbols include mathematical symbols and punctuation marks.
Example:

2)
Word Symbols
Word symbols, also called
reserved words
or
keywords
, are another type of token.
Reserved words are always lowercase and each is considered to be a single symbol and
have a special meaning. C++ Keywords
The following list shows the reserved words in C++. These
reserved words may
not be used as constant or variable or any other identifier
names.
auto
enum
operator
throw
bool
explicit
private
true
break
export
protected
try
case
extern
public
typedef
catch
false
register
typeid
char
float
reinterpret_cast
typename
class
for
return
union
const
friend
short
unsigned
con
st_cast
goto
signed
using
continue
if
sizeof
virtual
default
inline
static
void
delete
int
static_cast
volatile
do
long
struct
wchar_t
double
mutable
switch
while
literals
Keywords and Reserved Words :
Keywords are predefined identifiers, that are used in the syntax
and can be used as identifiers again.
Reserved words are the words in a programming language
which has a fixed meaning and cannot be redefined by the programmer.
They cannot be used as identifers(variables, functions etc).
• All reserved words and keywords are in lowercase letters.
• But be aware that this terminology is not standard. For example, In
some books it was mentioned that Reserved words are also called as
Reserved Keywords and some authors will use keyword in the same
sense that we have used Reserved word.
• Infact all keywords are subset of Reserve words.
• Keywords can be redefined while Reserved words cannot be
redefined and used.
For example :
#include<iostream>
using namespace std;
int main() // here main is the keyword
{
int main; // it can be redefined
main = 1;
cout<< main;
return 0;
}
Here main is the keyword. So it can be redefined and used as an
identifier.
Output :
1
#include <iostream>
using namespace std;
int main()
{
int auto;
auto = 1;
cout<< auto;
return 0;
}
Here auto is an Reserved word. It cannot be redefined. So it gives an error. In general
reserved words and keywords need not coincide, but in most modern programming languages,
keywords are a subset of reserved words, as this makes parsing easier, since keywords cannot
be confused with identifiers. In some languages, like C or Python, reserved words and
keywords coincide, while in other languages, like Java, all keywords are reserved words, but
some reserved words are not keywords – these are "reserved for future use".
Here is a list of Reserved words and keywords.

C++ Reserved Words

The reserved words of C++ may be conveniently placed into several groups. In the first
group, we put those that were also present in the C programming language and have been
carried over into C++. There are 32 such reserved words:
auto const double float int short struct unsigned
break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while

There are another 30 reserved words that were not in C, are therefore new to C++:
asm dynamic_cast namespace reinterpret_cast try
bool explicit new static_cast typeid
catch false operator template typename
class friend private this using
const_cast inline public throw virtual
delete mutable protected true wchar_t

The following 11 C++ reserved words are not essential when the standard ASCII character set
is being used, but they have been added to provide more readable alternatives for some of the
C++ operators, and also to facilitate programming with character sets that lack characters
needed by C++.
and bitand compl not_eq or_eq xor_eq
and_eq bitor not or xor

Some Predefined Identifiers

Beginning C++ programmers are sometimes confused by the difference between the two
terms reserved word and predefined identifier, and some potential for confusion.

One of the difficulties is that some keywords that one might "expect" to be reserved words are
not. The keyword main is a prime example, and others include things like the endl
manipulator and other keywords from the vast collection of C++ libraries.

For example, you could declare a variable called main inside your main function, initialize it,
and then print out its value (but ONLY do that to verify that you can!). On the other hand, you
could not do this with a variable named else. The difference is that else is a reserved word,
while main is "only" a predefined identifier.

Here is a short list of some predefined identifiers:

cin endl INT_MIN iomanip main npos std


cout include INT_MAX iostream MAX_RAND NULL string

LITERALS:
The data items which never change their value throughout the program run. There are several
kinds of literals:
· Integer literals
· Character literals
· Floating literals
· String literals
Integer literals :
Integer literals are whole numbers without any fractional part. An integer literal must have at
least one digit and must not contain any decimal point. It may contain either + or - sign. A
number with no sign is assumed as positive. C++ allows three types of integer literals:
(i) Decimal Integer Literals:- An integer literal without leading 0 (zero) is called
decimal integer literals e.g., 123, 786 , +97 , etc.
(ii) Octal Integer Literals:- A sequence of octal digit starting with 0 (zero) is taken to
be an octal integer literal ( zero followed by octal digits). e.g., 0345, 0123 , etc.
(iii) Hexadecimal Integer Literals :- Hexadecimal Integer Literals starts with 0x or 0X
followed by any hexa digits. e.g., 0x9A45, 0X1234, etc.
Character literals:
Any single character enclosed within single quotes is a character literal.
e.g ‘ A’ , ‘3’
Floating literals:
Numbers which are having the fractional part are referred as floating literals or real
literals. It may be a positive or negative number. A number with no sign is assumed to be a
positive number.
e.g 2.0, 17.5, -0.00256
String Literals:
It is a sequence of character surrounded by double quotes. e.g., “abc” , “23”.
PUNCTUATORS:
The following characters are used as punctuators which are also known as separators in
C++
[ ] { } ( ) , ; : * ……….. = #
Punctuator Name Function
[ ] Brackets These indicates single and multidimensional array subscripts
() Parenthesis These indicate function calls and function parameters.
{ } Braces Indicate the start and end of compound statements.
; Semicolon This is a statement terminator.
, Comma It is used as a separator.
: Colon It indicates a labeled statement
* Asterisk It is used as a pointer declaration
… Ellipsis These are used in the formal argument lists of function prototype to
indicate a variable number of arguments.
= Equal to It is used as an assigning operator.
# Pound sign This is used as preprocessor directives.

Variables:-A named memory location, whose contains can be changed with in program
execution is known as variable. OR
A variable is an identifier that denotes a storage location, which contains can be varied
during program execution.
Declaration of Variables:- All variables must be declared before they are used in executable
statements. Variable declaration reserves memory required for data storage and associates it with
a name. Syntax for variable declaration is:
datatypes variable_name1, variable_name2, variable_name3,……………. ;
e.g.,
int num;
int num, sum, avg;
We can also initialize a variable at the time of declaration by using following syntax:
datatypes variable_name = value;
e.g.,
int num = 0;
Constant:- A named memory location, whose contains cannot be changed with in program
execution is known as constant. OR
A constant is an identifier that denotes a storage location, which contains cannot be
varied during program execution.
Syntax for constant declaration is:
const datatypes constant_name = value ;
e.g.,
const float pi = 3,14f ;
Operators:-
Arithmetic operators :-Those operators are operates only on numeric data types operands are
known as arithmetic operators.
Operator Operation Example
Unary - Result is the negation of
operand’s value (Reverse the
sign of operand’s value)
If a=5 then – a means -5.
If a = - 4 then – a means 4.

Unary + The result is the value of its


operand
If a=5 then +a means 5.
If a = - 4 then +a means -4.
+
(Addition Operator)
Addition ( it adds two
numbers)
4+20 results is 24.
If a = 5 then a + 5 results 10.
-
( Subtraction Operator)
Subtraction ( Subtract the
second operand from first)
14 – 3 evaluates to 12.
If a = 2 , b = 3 then b – a
evaluates 1.
*
(Multiplication Operator)
Multiplies the values of its
operands
3*4 evaluates to 12.
If a=2, b=3 then a*b evaluates
to 6.
/
(Division Operator)
Divides its first operand by the
second
100/5 evaluates 20.
If a =10 , b = 5 then a/b
evaluates 2
%
(Modulus Operator)
It produce the remainder of
dividing the first operand by
second
19%6 evaluates to 1.
If a = 14 , b = 3 then a%b
evaluates to 2.
Modulus operator requires that
both operands be integer and
second operand be non-zero.
Increment and Decrement Operators (++ , - -) :
The increment operator (++) adds 1 to its operand and decrement operator (--) subtract one from
its operand. In other word
a = a + 1; is same as ++a; or a++;
& a = a – 1 ; is same as --a; or a--;
Both the increment & decrement operators comes in two version :
(i) Prefix increment/decrement :- When an increment or decrement operator precedes its
operand, it is called prefix increment or decrement (or pre-increment / decrement). In
prefix increment/decrement , C++ perform the increment or decrement operation
before using the value of the operand. e.g.,
If sum = 10 and count =10 then
Sum = sum +(++count);
First count incremented and then evaluate sum = 21.
(ii) Postfix increment/decrement :- When an increment or decrement operator follows its
operand, it is called postfix increment or decrement (or post-increment / decrement).
In postfix increment/decrement , C++ first uses the value of the operand in evaluating
the expression before incrementing or decrementing the operand’s value. e.g.,
If sum = 10 and count =10 then
Sum = sum +(count++);
First evaluate sum = 20 , and then increment count to 11.
Relational Operator: These operators are used to compare two values. If comparison is true,
the relational expression results into the value 1 and if the comparison is false its result will be 0.
The six relational operators are:
Operator Meaning
= = Equal to
!= Not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
Logical Operators : In addition to the relational operator, C++ contains three logical
operators. Relational operators often are used with logical operators to construct more complex
decision making expressions.
Operators Use Return True if
&& (Logical AND) op1 && op2 op1 and op2 are both true
|| (Logical OR) op1 || op2 Either op1 or op2 is true
! (Logical NOT) !op1 op1 is false (it is unary operator)
Assignment Operator: C++ offers an assignment operator (=) to assign a value to an
identifier. The assignment statement that make use of this operator are written in the form :
var = expression ;
where var generally represents a variable and expression may be a constant or a variable or an
expression.
C++ offers special shorthand operators that simplify the coding of a certain type of assignment
statement . e.g.,
a = a + 10 ; can be written as a+=10 ;
This shorthand works for all binary arithmetic operators. The general form of this shorthand is
Var = var operator expression ; is same as
var operator = expression ;
Following are some examples of C++ shorthands:
x -=10 ; equivalent to x = x -10 ;
x*=3 ; equivalent to x = x * 3 ;
x/=2 ; equivalent to x = x/2 ;
x%=z equivalent to x = x % z ;
Conditional operator ( ? : )
The conditional operator (? :) is a ternary operator i.e., it require three operands. The general
form of conditional operator is:
expression1? expression2: expression3 ;
Where expression1 is a logical expression , which is either true or false.
If expression1 evaluates to true i.e., 1, then the value of whole expression is the value of
expression2, otherwise, the value of the whole expression is the value of expression3. For
example min = a<b? a : b ;
Here if expression (a<b ) is true then the value of a will be assigned to min otherwise value of b
will be assigned to min.
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only
one expression is expected. When the set of expressions has to be evaluated for a value, only the
rightmost expression is considered.
For example, the following code:
a = (b =3 , b +2 );
Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a
would contain the value 5 while variable b would contain value 3.
sizeof()
This operator returns the size of its operand in bytes. The operand may be an expression
or identifier or it may be a data type.
a= sizeof (char);
This will assign the value 1 to a because char is a one-byte long type.
Data Types
Data Type
: set of values together with a set of operations is called a data type
C++ data can be classified into three categories:
Simple data type, Structured data
type, Pointers
9300110033

9302511111

Operators Precedence in C++


Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator *
has higher precedence than +, so it first gets multiplied with 3*2 and then adds
into 7.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right

Additive + - Left to right


Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

Statement Flow Control:-In a program , statements may be executed sequentially,


selectively, or iteratively.

Every programming language provides three constructs:

1. Sequence Constructs

2. Selection Constructs

3. Iteration Constructs
Sequence Construct:-The sequence construct means the statements
are being executed sequentially. It represents the default flow of
statements.

Looping or Iteration Statements:-Looping the iteration construct means repetition of set of


statements depending upon a condition test. The iteration statements allow a set of instructions to be
performed repeatedly until a certain condition is true.

Body of Loop

Loop condition

There are two types of loops:-


1. Entry-controlled loop :-In entry-controlled loop first of
all loop condition is checked and then body of loop is
executed is condition is true. If loop condition is false in
the starting the body of loop is not executed even once.

2. Exit-controlled loop :-In exit-controlled loop first body of


loop is executed once and then loop condition is checked.
If condition is true then the body of loop will be executed
again.

It means in this type of loop, loop body will be executed


once without checking loop condition.

Selection Statements :-There are two types of selection statements in C++ :

1. if statement

2. switch statement

if Statement : If statement have three forms


(a) if … else Statement :- It is useable, when we have to performs an action if a condition is True and
we have to perform a different action if the condition is false. The syntax of if…else statement is:
if ( < conditional expression > )

< statement-1 or block-1>;

/ statements to be executed when conditional expression is true.

else
{

< statement-2 or block-2>;

/ statements to be executed when conditional expression is false.

If the <conditional expression> is evaluated to true then the < statement-1 or block-1> (statement under
if ( ) block ) will be executed otherwise the <statement-2 or block-2> (statements under else block)
would be executed. if there exists only one program statement under if( ) block then we may omit curly
braces { }.

(b) Simple if statement:- The else part in if … else statement is optional, if we omit
the else part then it becomes simple if statement. This statement is usable, when we
have to either perform an action if a condition is True or skips the action if the
condition is false. The syntax of simple if statement is:

if ( < conditional expression > )

< statement-1 or block-1>;

/ statements to be executed when conditional expression is true.

Here <statement-1 or block-1> will be executed only if <conditional expression > evaluates true.

if there exists only one program statement under if( ) block then we may omit curly braces { }.

(c) The if-else-if ladder :-This statement allows you to test a number of mutually exclusive cases and
only execute one set of statements for which condition evaluates true first.
The syntax is:

if ( <condition -1> )

statement-1; // do something if condition-1 is satisfied (True)

else if ( <condition – 2 >)


statement-3 ; // do something if condition -2 is satisfied (True)

else if (<condition – 3 >)


statement-3 ;

: // many more n-1 else - if ladder may come

:
else if( < condition – n >)

statement-n ;

else

statement-m ;

}
}

2. switch Statement :-This is multi-branching statement. Syntax of this statement is as follows:

switch (expression/variable)

{case value_1: statement -1;

break;

case value_2: statement -2;

break;

case value_n: statement -n;

break;

[ default: statement -m ]

Note: expression/variable should be integer or character type only.

When the switch statement is executed, the expression/variable is evaluated and control is transferred directly to
the statement whose case label value matches the value of expression/ variable. If none of the case label value
matches the value of expression/variable then only the statement following the default will be executed. If no
default statement is there and no match is found then no action take place. In this case control is transferred to
the statement that follows the switch statement.

Dereference operator
Updated: 04/26/2017 by Computer Hope

In computer programming, a dereference operator, also known as an indirection operator,


operates on a pointer variable, and returns the location-value, or l-value that it points to in
memory. In the C programming language, the deference operator is denoted with an asterisk (*).
For example, in C, we can declare a variable x, that holds an integer value, and a variable p,
which holds a pointer to an integer value in memory:

int x; int *p;

Here, the asterisk tells the compiler, "p is not an integer, but rather a pointer to a location in
memory which holds an integer." Here, it is not a dereference, but part of a pointer declaration.

Now we can set p to the location allocated for the value of x using the & operator, which means
"address of."

p = &x;

This action tells the compiler, "The address in memory that p points to is the address that you
allocated for the integer x."

To illustrate: if we set the value of x to 1 using the conventional method, and print the value, the
output will be 1.

x = 1; printf("%d", x);

However, we can also change the value of x by referencing p. We do this with an asterisk:

*p = 2; printf("%d", x);

And the output changes to 2.

In other words, after p has been declared as a pointer of the same type as x and then set to point
to x's value, we can use x and *p interchangeably. Since they both refer to the same thing,
changing the value of one will change the value of the other.

You might also like