0% found this document useful (0 votes)
16 views19 pages

Chapter 4 - C++ Basics

Chapter 2 covers the basics of C++ programming, including the structure of a C++ program, the development cycle, and the process of writing, compiling, and linking code. It explains key concepts such as input/output operations, keywords, identifiers, and variables, along with their declarations and initialization. The chapter also emphasizes the importance of syntax and semantics in programming, highlighting how they contribute to meaningful code execution.

Uploaded by

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

Chapter 4 - C++ Basics

Chapter 2 covers the basics of C++ programming, including the structure of a C++ program, the development cycle, and the process of writing, compiling, and linking code. It explains key concepts such as input/output operations, keywords, identifiers, and variables, along with their declarations and initialization. The chapter also emphasizes the importance of syntax and semantics in programming, highlighting how they contribute to meaningful code execution.

Uploaded by

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

Chapter 2

2. C++ Basics
2.1. Structure of C++ Program

A C++ program has the following structure


[Comments]
[Preprocessor directives]
[Global variable declarations]
[Prototypes of functions]
[Definitions of functions]
2.2. C++ IDE
The complete development cycle in C++ is: Write the program, compile the source code, link the
program, and run it.

Writing a Program
To write a source code, your compiler may have its own built-in text editor, or you may be using
a commercial text editor or word processor that can produce text files. The important thing is that
whatever you write your program in, it must save simple, plain-text files, with no word
processing commands embedded in the text. Examples of safe editors include Windows Notepad,
the DOS Edit command, EMACS, and vi. Many commercial word processors, such as
WordPerfect, Word, and dozens of others, also offer a method for saving simple text files. The
files you create with your editor are called source files, and for C++ they typically are named
with the extension .CPP.
Compiling
Your source code file can't be executed, or run, as a program can. To turn your source code into a
program, you use a compiler. How you invoke your compiler, and how you tell it where to find
your source code, will vary from compiler to compiler; check your documentation. In Borland's
Turbo C++ you pick the RUN menu command. After your source code is compiled, an object
file is produced. This file is often named with the extension .OBJ. This is still not an executable
program, however. To turn this into an executable program, you must run your linker.
Linking
C++ programs are typically created by linking together one or more OBJ files with one or more
libraries. A library is a collection of linkable files that were supplied with your compiler, that you
purchased separately, or that you created and compiled. All C++ compilers come with a library
of useful functions (or procedures) and classes that you can include in your program. A function
is a block of code that performs a service, such as adding two numbers or printing to the screen.
A class is a collection of data and related functions.
Summary
The steps to create an executable file are
1. Create a source code file, with a .CPP extension.
2. Compile the source code into a file with the .OBJ extension.
3. Link your OBJ file with any needed libraries to produce an executable program.
But the process of writing a C++ program contains the following:

2.3. Showing Sample Program


Any meaningful program written in C++ has to contain a number of components: the main
function; some variable declarations; and some executable statements. For example, the
following is a very basic C++ program:
The first panel shows the source code for our first program. The second one shows the result of
the program once compiled and executed. The way to edit and compile a program depends on the
compiler you are using. Depending on whether it has a Development Interface or not and on its
version. Consult the compilers section and the manual or help included with your compiler if you
have doubts on how to compile a C++ console program.
❖ // my first program in C++ this is a comment line. All lines beginning with two slash signs
(//) are considered comments and do not have any effect on the behavior of the program.

❖ #include <iostream> Lines beginning with a hash sign (#) are directives for the preprocessor.
They are not regular code lines with expressions but indications for the compiler's preprocessor.
In this case the directive #include <iostream> tells the preprocessor to include the iostream
standard file. This specific file (iostream) includes the declarations of the basic standard
input/output library in C++, and it is included because its functionality is going to be used later
in the program.
❖using namespace std; All the elements of the standard C++ library are declared within what
is called a namespace, the namespace with the name std. So, in order to access its functionality,
we declare with this expression that we will be using these entities. This line is very frequent in
C++ programs that use the standard library, and in fact it will be included in most of the source
codes.
❖int main (): This line corresponds to the beginning of the definition of the main function.
The main function is the point by where all C++ programs start their execution, independently of
its
location within the source code. It does not matter whether there are other functions with other
names defined before or after it - the instructions contained within this function's definition will
always be the first ones to be executed in any C++ program. For that same reason, it is essential
that all C++ programs have a main function. The word main is followed in the code by a pair of
parentheses (()). That is because it is a function declaration.
❖cout << "Hello World!"; This line is a C++ statement. A statement is a simple or compound
expression that can actually produce some effect. In fact, this statement performs the only
action that generates a visible effect in our first program.
 cout represents the standard output stream in C++, and the meaning of the entire
statement
is to insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (which usually is the screen).
 cout is declared in the iostream standard file within the std namespace, so that's why we
needed to include that specific file and to declare that we were going to use this specific
namespace earlier in our code.
❖return 0; The return statement causes the main function to finish. return may be followed by
a return code (in our example is followed by the return code 0). A return code of 0 for the main
function is generally interpreted as the program worked as expected without any errors during its
execution. This is the most usual way to end a C++ console program.

C++ Terminology and Syntax


1 /*
2 First C++ program that says hello (hello.cpp)
3 */
4 #include <iostream> // Needed to perform IO operations
5 using namespace std;
6
7 int main() { // Program entry point
8 cout << "hello, world" << endl; // Say Hello
9 return 0; // Terminate main()
10 } // End of main function

Statement: A programming statement performs a piece of programming action. It must be


terminated by a semicolon (;) just like an English sentence is ended with a period﴿, as in Lines 5,
8 and 9.

Preprocessor Directive: The #include ﴾Line 4﴿ is a preprocessor directive and NOT a


programming statement. A preprocessor directive begins with hash sign ﴾#﴿. It is processed
before
compiling the program. A preprocessor directive is NOT terminated by a semicolon - take note
of
this unusual rule.
Block: A block is a group of programming statements enclosed by braces { }. This group of
statements is treated as one single unit. There is one block in this program, which contains the
body of the main() function. There is no need to put a semicolon after the closing brace.
Comments: A multi-line comment begins with /* and ends with */, which may span more than
one line. An end-of-line comment begins with // and lasts till the end of the line. Comments are
not executable statements and are ignored by the compiler; but they provide useful explanation
and documentation. Use comments liberally.
Whitespaces: Blank, tab, and newline are collectively called whitespaces. Extra whitespaces are
ignored, i.e., only one whitespace is needed to separate the tokens. Nevertheless, extra white
spaces and newlines could help you and your readers better understand your program. Use extra
whitespaces and newlines liberally.
Case Sensitivity: C++ is case sensitive - a ROSE is NOT a Rose, and is NOT a rose.

Syntax and Semantics


The Syntax of a programming language consists of the rules for the correct use of the language.
This involves the correct grammatical construction and arrangement of the language, correct
spelling, hyphenation, inflection and so on.
The semantics of a programming language deal with the meanings given to syntactically correct
constructs of the language. Usually, semantics is defined in terms of the program’s run-time
behavior: What happens when the program is executed with a certain set of inputs, what
statements are executed, what values are assigned to the variables, and what output is produced.
Thus, syntax has nothing to do with “meaning” or run-time behavior of a program. A program
could be syntactically correct yet meaningless. The program below (code fragment) is
syntactically correct but does not have any meaning at runtime (never terminates).
sum=0;
while (sum! =-1)
sum=sum+10;
Yet syntax is a prerequisite to meaningful expression. Thus, a programming language must have
a good syntactic definition before it can properly support the development of meaningful
programs.
2.4. Basic Elements
2.4.1. Input and Output (cin and cout respectively)

 Cout is an object used for printing data to the screen.


 To print a value to the screen, write the word cout, followed by the insertion operator also
called output redirection operator (<<) and the object to be printed on the screen.
Syntax: Cout<<Object;
The object at the righthand side can be:
• A literal string: “Hello World”
• A variable: a place holder in memory
 Cin is an object used for taking input from the keyboard.
 To take input from the keyboard, write the word cin, followed by the input redirection
operator (>>) and the object name to hold the input value.
Syntax: Cin>>Object
 Cin will take value from the keyboard and store it in the memory. Thus, the cin statement
needs a variable which is a reserved memory place holder.
 Both << and >> return their right operand as their result, enabling multiple input or
multiple output operations to be combined into one statement. The following example
will illustrate how multiple input and output can be performed:
E.g.:
 Cin>>var1>>var2>>var3;
Here three different values will be entered for the three variables. The input should be
separated by a space, tan or newline for each variable.
 Cout<<var1<<”, “<<var2<<” and “<<var3;
Here the values of the three variables will be printed where there is a “,” (comma)
between the first and the second variables and the “and” word between the second and
the third.

2.4.2. Keywords

A keyword is a reserved word that has a predefined meaning and purpose in the language. These
are keywords used by the compiler to control your program. It cannot be used as an identifier by
the user in his program e.g. float, int, main and so on. Every language has its own set of key
words. Note that all reserved words are in lower case letters. The list of the keywords present in
C++ is given below.

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do,
double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline,
int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast,
return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try,
typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while, and,
and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

Notice that main is not a reserved word. However, this is a fairly technical distinction, and for
practical purposes you are advised to treat main, cin, and cout as if they were reserved as well.

2.4.3. Identifiers

It is the symbolic name given by a programmer for any data item or function. The identifier is a
sequence of characters taken from the C++ character set. The rules for the formation of an
identifier are:
 Can consist of alphabets (a-z or A-Z), digits (0-9) and only one special character i.e.
underscore “_”. i.e. neither space nor marked letters can be part of an identifier.
 Can start with an alphabet or underscore, but not with a digit.
 C++ is case sensitive language
 Can’t be reserved words. i.e. keywords should not be used as a name for identifiers.
For the purposes of C++ identifiers, the underscore symbol, _, is considered to be a letter. Its use
as the first character in an identifier is not recommended though, because many library functions
in C++ use such identifiers. Similarly, the use of two consecutive underscore symbols, _ _, is
forbidden. For example, Length, Int, today, a9, … are valid identifiers.
Note: The C ++ language is “case sensitive “, that means that an identifier written in capital letters
is not equivalent to another one with the same name but written in small letters. E.g. the variable
Extension is not identical with variable extension.

2.4.4. Variables

Variables are also a kind of identifiers. They are the most fundamental part of any language. A
variable is a location in the computer memory which can store data and is given a symbolic name
for a memory location in which data can be stored and subsequently recalled (easy reference).
Variables are used for holding data values so that they can be utilized in various computations in
a program. Its value can change during the program execution. All variables have three important
attributes:
 A type, which is, established when the variable is defined (e.g., integer, float, character).
Once defined, the type of a C++ variable cannot be changed.
 A name, a name which will be used to refer to the value in the variable.
A unique identifier for the reserved memory location.
 A value, which can be changed by assigning a new value to the variable. The kind of
values a variable can assume depends on its type. For example, an integer variable can
only take integer values (e.g., 2, 100, -12) not real numbers like 0.123.
2.4.4.1. Variable Declaration
Declaring a variable means defining (creating) a variable. You create or define a variable by
stating its type, followed by one or more spaces, followed by the variable name and a semicolon.
The variable name must satisfy the identifiers naming rule. Good variable names tell you what
the variables are for; using good names makes it easier to understand the flow of your program.
The syntax for declaring a variable is given below:
< data type > < variable name >;
In the syntax given above, the ‘data type’ parameter has to be any one of the data types present in
C++ (int, long, char, float, double, etc.). The following statement defines an integer variable
called myAge:
Int myAge;

Note that variables must be declared before used. As a general programming practice, avoid
such horrific names as J23qrsnf, and restrict single-letter variable names (such as x or i) to
variables that are used only very briefly. Try to use expressive names such as myAge or
howMany.
2.4.4.2. Creating More Than One Variable at a Time
You can create more than one variable of the same type in one statement by writing the type and
then the variable names, separated by commas. For example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
As you can see, myAge and myWeight are each declared as integer variables. The second line
declares three individual long variables named area, width, and length. However, keep in mind
that you cannot mix types in one definition statement.
2.4.4.3. Assigning Values to Your Variables
You assign a value to a variable by using the assignment operator (=). Thus, you would assign 5
to Width by writing
int Width;
Width = 5;
You can combine these steps and initialize Width when you define it by writing
int Width = 5;
Initialization looks very much like assignment, and with integer variables, the difference is
minor. The essential difference is that initialization takes place at the moment you create the
variable.
Just as you can define more than one variable at a time, you can initialize more than one variable
at creation. For example:
// create two int variables and initialize
them
int width = 5, length = 7;
This example initializes the integer variable width to the value 5 and the length variable to the
value 7. It is possible to even mix definitions and initializations:
int myAge = 39, yourAge, hisAge =
40;
This example creates three type int variables, and it initializes the first and third.

2.4.4.4. Scope of Variables


 Scope of a variable is the boundary or block in a program where a variable can be
accessed. The boundary or block is identified by the left and right French brackets.
 In C++, we can declare variables anywhere in the source code. But we should
declare a variable before using it no matter where it is written.
 Global variables: are variables that can be referred/accessed anywhere in the code,
within any function, as long as it is declared first. A variable declared before any
function immediately after the include statements are global variables.
 Local Variables: the scope of the local variable is limited to the code level or
block within which they are declared.
 In the following example, the integer data type num1 is accessible everywhere
whereas z and is only accessible in the add function and num2 is accessible in
main function. This means cout<<z; or any statement involving z is only valid in
add function.
 For example,

#include<iostream.h>
int num1;
int add( int x, int y)
{
int z;
….
}
void main()
{
unsigned short age;
float num2;
cout<<”\n Enter your age:”;

}

 In C++ the scope of a local variable is given by the block in which it is declared.
 If it is declared within a function, it will be a variable with a function scope. If it
is declared in a loop, its scope will be only in the loop, etc.

2.4.5. Basic Data Types

When you define a variable in C++, you must tell the compiler what kind of variable it is: an
integer, a character, and so forth. This information tells the compiler how much room to set aside
and what kind of value you want to store in your variable. Several data types are built into C++.
The varieties of data types allow programmers to select the type appropriate to the needs of the
applications being developed. The data types supported by C++ can be classified as basic
(fundamental) data types, user defined data types, derived data types and empty data types.
However, the discussion here will focus only on the basic data types.
Basic (fundamental) data types in C++ can be conveniently divided into numeric and character
types. Numeric variables can further be divided into integer variables and floating-point
variables. Integer variables will hold only integers whereas floating number variables can
accommodate real numbers. Both the numeric data types offer modifiers that are used to vary the
nature of the data to be stored. The modifiers used can be short, long, signed and unsigned. The
following table shows the variable type, how much room it takes in memory, and what kinds of
values can be stored in these variables. The values that can be stored are determined by the size
of the variable types.
Type Size Values
unsigned short int 2 bytes 0 to 65,535
short int(signed short int) 2 bytes -32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long int) 4 bytes -2,147,483,648 to 2,147,483,647
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
Char 1 byte 256-character values
Float 4 bytes 3.4e-38 to 3.4e38
Double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932
Bool 1 byte True/false (top 7 bits are ignored)
Signed and Unsigned
 Signed integers are either negative or positive.
 Unsigned integers are always positive.
 Because both signed and unsigned integers require the same number of bytes, the largest
number (the magnitude) that can be stored in an unsigned integer is twice as the largest
positive number that can be stored in a signed integer.
 E.g.: Lets us have only 4 bits to represent numbers
Unsigned Signed
Binary Decimal Binary Decimal
0 0 0 0 →0 0000→0
0 0 0 1 →1 0001→1
0 0 1 0 →2 0010→2
0 0 1 1 →3 0011→3
0 1 0 0 →4 0100→4
0 1 0 1 →5 0101→5
0 1 1 0 →6 0110→6
0 1 1 1 →7 0111→7
1 0 0 0 →8 1000→0
1 0 0 1 →9 1001→ -1
1 0 1 0 →10 1010 → -2
1 0 1 1 →11 1011 → -3
1 1 0 0 →12 1100 → -4
1 1 0 1 →13 1101 → -5
1 1 1 0 →14 1110 → -6
1 1 1 1 →15 1111 → -7
 In the above example, in case of unsigned, since all the 4 bits can be used to represent the
magnitude of the number the maximum magnitude that can be represented will be 15 as
shown in the example.
 If we use signed, we can use the first bit to represent the sign where if the value of the
first bit is 0 the number is positive if the value is 1 the number is negative. In this case we
will be left with only three bits to represent the magnitude of the number. Where the
maximum magnitude will be 7.

Characters
 Characters variables (type char) are typically one byte in size, enough to hold 256 different
values. A char can be represented as a small number (0 - 255).
 Char in C++ are represented as any value inside a single quote.
E.g.: ‘x’, ‘A’, ‘5’, ‘a’, etc.
 When the compiler finds such values (characters), it translates back the value to the ASCII
values. E.g. ‘a’ has a value 97 in ASCII.

Special Printing characters


 In C++, there are some special characters used for formatting. These are:
\n new line \t tab
\b backspace \” double quote
\’ single quote \? Question mark
\\ backslash

2.4.6. Constants

 A constant is any expression that has a fixed value.


 Like variables, constants are data storage locations in the computer memory. But, constants,
unlike variables their content cannot be changed after the declaration.
 Constants must be initialized when they are created by the program, and the programmer
can’t assign a new value to a constant later.
 C++ provides two types of constants: literal and symbolic constants.
i. Literal constant: is a value typed directly into the program wherever it is needed.
E.g.: int num = 43;
43 s a literal constant in this statement:
ii. Symbolic constant: is a constant that is represented by a name, similar to that of a
variable. But unlike a variable, its value can’t be changed after initialization.
E.g.: Int studentPerClass =15;
students = classes * studentPerClass;
studentPerClass is a symbolic constant having a value of 15. And 15 is a literal constant
directly typed in the program.
 In C++, we have two ways to declare a symbolic constant. These are using the #define and
the const key word.

Defining constants with #define


 The #define directive makes a simple text substitution.
 The define directive can define only integer constants
E.g.: #define studentPerClass 15
 In our example, each time the preprocessor sees the word studentPerClass, it inserts 15 into
the text.
Defining constants with the const key word
 Here, the constant has a type, and the compiler can ensure that the constant is used
according to the rules for that type.
E.g.: const unsigned short int studentPerClass = 15;

Enumerated constants
 Used to declare multiple integer constants using a single line with different features.
 Enables programmers to define variables and restrict the value of that variable to a set of
possible values which are integer.
 The enum type cannot take any other data type than integer
 enum types can be used to set up collections of named integer constants. (The keyword enum
is short for “enumerated''.)
 The traditional way of doing this was something like this:
#define SPRING 0
#define SUMMER 1
#define FALL 2
 An alternate approach using enum would be
enum SEASON{ SPRING, SUMMER, FALL, WINTER };
 You can declare COLOR to be an enumeration, and then you can define five possible values
for COLOR: RED, BLUE, GREEN, WHITE and BLACK.
E.g.: enum COLOR {RED,BLUE,GREEN,WHITE,BLACK};
 Every enumerated constant has an integer value. If the programmer does not specify
otherwise, the first constant will have the value 0, and the values for the remaining constants
will count up from the initial value by 1. thus in our previous example RED=0, BLUE=1,
GREEN=3, WHITE=4 and BLACK=5
 But one can also assign different numbers for each.
E.g.: enum COLOR{RED=100,BLUE,GREEN=500,WHITE,BLACK};
Where RED will have 100 and BLUE will have 101 while GREEN will have 500, WHITE 501 and
BLACK 502.
2.4.7. Comments

A comment is a piece of descriptive text which explains some aspect of a program. Program
comments are text totally ignored by the compiler and are only intended to inform the reader
how the source code is working at any particular point in the program. C++ provides two types
of comment delimiters:
i. Single Line Comment: Anything after // {double forward slash} (until the end of the line
on which it appears) is considered a comment. Eg:
cout<<var1; //this line prints the value of var1
ii. Multiple Line Comment: Anything enclosed by the pair /* and */ is considered a
comment. Eg:
/* this is a kind of comment where
Multiple lines can be enclosed in
one C++ program */
 Comments should be used to enhance (not to hinder) the readability of a program. The following two
points, in particular, should be noted:
i. A comment should be easier to read and understand than the code which it tries to explain. A
confusing or unnecessarily-complex comment is worse than no comment at all.
ii. Over-use of comments can lead to even less readability. A program which contains so much
comment that you can hardly see the code can by no means be considered readable.
iii. Use of descriptive names for variables and other entities in a program, and proper indentation
of the code can reduce the need for using comments.

2.5. Operators
 An operator is a symbol that makes the machine to take an action.
 Different Operators act on one or more operands and can also have different kinds of
operators.
 C++ provides several categories of operators, including the following:
o Assignment operator
o Arithmetic operator
o Relational operator
o Logical operator
o Bitwise operator
o Increment/decrement operator
o Conditional operator
o Comma operator
o The size of operator
o Explicit type casting operators, etc
2.5.1. Assignment operator (=).

 The assignment operator causes the operand on the left side of the assignment statement
to have its value changed to the value on the right side of the statement.
 Syntax: Operand1=Operand2;
 Operand1 is always a variable
 Operand2 can be one or combination of:
• A literal constant: Eg: x=12;
• A variable: Eg: x=y;
• An expression: Eg: x=y+2;

2.5.1.1. Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=).
 Compound assignment operator is the combination of the assignment operator with other
operators like arithmetic and bitwise operators.
 The assignment operator has a number of variants, obtained by combining it with other
operators.
 E.g.:
value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a – 5;
a /= b; is equivalent to a = a / b;
price *= units + 1 is equivalent to price = price * (units + 1);
 And the same is true for the rest.

2.5.2. Arithmetic operators (+, -, *, /, %).

 Except for remainder or modulo (%), all other arithmetic operators can accept a mix of
integers and real operands. Generally, if both operands are integers then, the result will be
an integer. However, if one or both operands are real then the result will be real.
 When both operands of the division operator (/) are integers, then the division is
performed as an integer division and not the normal division we are used to.
 Integer division always results in an integer outcome.
 Division of integer by integer will not round off to the next integer
 E.g.:
9/2 gives 4 not 4.5
-9/2 gives -4 not -4.5
 To obtain a real division when both operands are integers, you should cast one of the
operands to be real.
 E.g.:
int cost = 100;
Int volume = 80;
Double unitPrice = cost/(double)volume;
 The module(%) is an operator that gives the remainder of a division of two integer
values. For instance, 13 % 3 is calculated by integer dividing 13 by 3 to give an outcome
of 4 and a remainder of 1; the result is therefore 1.
 E.g.:
a = 11 % 3
a is 2

2.5.3. Relational operator (==, !=, > , <, >=, <=).

 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)

2.5.4. Bitwise operator

 C++ provides six bitwise operators for manipulating the individual bits in an integer
quantity. These are summarized in the table below.
Operator Name Example

~ Bitwise Negation ~'\011' // gives '\366'

& Bitwise And '\011' & '\027' // gives '\001'

| Bitwise Or '\011' | '\027' // gives '\037'

^ Bitwise Exclusive '\011' ^ '\027' // gives '\036'


Or

<< Bitwise Left Shift '\011' << 2 // gives '\044'

>> Bitwise Right Shift '\011' >> 2 // gives '\002'

Bitwise operators expect their operands to be integer quantities and treat them as bit sequences.
Bitwise negation is a unary operator which reverses the bits in its operands. Bitwise and
compares the corresponding bits of its operands and produces a 1 when both bits are 1, and 0
otherwise. Bitwise or compares the corresponding bits of its operands and produces a 0 when
both bits are 0, and 1 otherwise. Bitwise exclusive or compares the corresponding bits of its
operands and produces a 0 when both bits are 1 or both bits are 0, and 1 otherwise.
Bitwise left shift operator and bitwise right shift operator both take a bit sequence as their left
operand and a positive integer quantity n as their right operand. The former produces a bit
sequence equal to the left operand but which has been shifted n bit positions to the left. The latter
produces a bit sequence equal to the left operand but which has been shifted n bit positions to the
right. Vacated bits at either end are set to 0.

2.5.5. Logical Operators (!, &&, ||):

 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.
 E.g.:
!20 //gives 0
10 && 5 //gives 1
10 || 5.5 //gives 1
10 && 0 // gives 0
N.B. In general, any non-zero value can be used to represent the logical true, whereas
only zero represents the logical false.

2.5.6. 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.
2.5.6.1. Prefix and Postfix:
 The prefix type is written before the variable. Eg (++ myAge), whereas the postfix type
appears after the variable name (myAge ++).
 Prefix and postfix operators can not be used at once on a single variable: Eg: ++age-- or
--age++ or ++age++ or - - age - - is invalid
 In a simple statement, either type may be used. But in complex statements, there will be a
difference.
 The prefix operator is evaluated before the assignment, and the postfix operator is
evaluated after the assignment.

E.g.
int k = 5;
(auto increment prefix) y= ++k + 10; //gives 16 for y
(auto increment postfix) y= k++ + 10; //gives 15 for y
(auto decrement prefix) y= --k + 10; //gives 14 for y
(auto decrement postfix) y= k-- + 10; //gives 15 for y

2.5.7. Conditional Operator (?:)

 The conditional operator takes three operands. It has the general form:
Syntax: operand1? operand2: operand3
 First operand1 is a relational expression and will be evaluated. If the result of the
evaluation is non-zero (which means TRUE), then operand2 will be the final result.
Otherwise, operand3 is the final result.
E.g.: General Example
Z= (X<Y? X: Y)
This expression means that if X is less than Y the value of X will be
assigned to Z otherwise (if X>=Y) the value of Y will be assigned to Z.
E.g.:
int m=1,n=2,min;
min = (m < n ? m : n);
The value stored in min is 1.
E.g.:
(7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5

2.5.8. Comma Operator (,).

 Multiple expressions can be combined into one expression using the comma operator.
 The comma operator takes two operands. Operand1, Operand2
 The comma operator can be used during multiple declaration, for the condition operator
and for function declaration, etc
 It the first evaluates the left operand and then the right operand, and returns the value of
the latter as the final outcome.
E.g.
int m,n,min;
int mCount = 0, nCount = 0;
min = (m < n ? (mCount++ , m) : (nCount++ , n));
Here, when m is less than n, mCount++ is evaluated and the value of m is stored in min.
otherwise, nCount++ is evaluated and the value of n is stored in min.

2.5.9. The sizeof() Operator.

 This operator is used for calculating the size of any data item or type.
 It takes a single operand (e.g. 100) and returns the size of the specified entity in bytes.
The outcome is totally machine dependent.
E.g.:
a = sizeof(char)
b = sizeof(int)
c = sizeof(1.55) etc

2.5.10. Explicit type casting operators.

 Type casting operators allows you to convert a datum of a given type to another data
type.
E.g.
int i;
float f = 3.14;
i = (int)f; equivalent to i = int(f);
Then variable i will have a value of 3 ignoring the decimal point.
2.6. Operator Precedence
 The order in which operators are evaluated in an expression is significant and is
determined by precedence rules. Operators in higher levels take precedence over
operators in lower levels. Precedence Table:
Level Operator Order
Highes sizeof() ++ -- (pre fix) Right to
t left
* / % Left to
right
+ - Left to
right
< <= > >= Left to
right
== != Left to
right
&& Left to
right
|| Left to
right
? : Left to
right
= ,+=, -=, *=, /=,^= ,%=, &= ,| Right to
= ,<<= ,>>= left
++ -- (postfix) Left to
right
, Left to
right
E.g.
a==b+c*d
c * d is evaluated first because * has a higher precedence than + and = =.
The result is then added to b because + has a higher precedence than = =.
And then == is evaluated.
 Precedence rules can be overridden by using brackets.
E.g. rewriting the above expression as:
a = = (b + c) * d causes + to be evaluated before *.
 Operators with the same precedence level are evaluated in the order specified by the
column on the table of precedence rule.
E.g. a = b += c the evaluation order is right to left, so the first b += c is evaluated
followed by a = b.

You might also like