Group Number 1
Leader:
Bryan M. Bejec
Members:
Asaytono, Marick John S.
Cano, Aldrin
Dizon, Ezekiel
Atienza, Aimee
Vanessa, Laxa
Miranda, Mailalyn Ann
Ms. Robell H. Samson
Teacher in Programming
TURBO C
C Programming Keywords and Identifiers
Character set
Character set is a set of alphabets, letters and some special characters that are valid in C
language.
Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits
0123456789
Special Characters
, < > . _
( ) ; $ :
% [ ] # ?
^ ! * / |
- \ ~ +
blank space, new line, horizontal tab, carriage return and form feed
C Keywords
Keywords are predefined, reserved words used in programming that have special meanings to the
compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:
int money;
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all
keywords allowed in ANSI C.
Keywords in C Programming
This statement suggests that var1 is a variable of storage class auto and type int.
Variables declared within function bodies are automatic by default. They are recreated each time
a function is executed.
It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.
break Statement
The break statement terminates the loop (for, while and do...while loop) immediately when it is
encountered. The break statement is used with decision making statement such as if...else.
break;
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
printf("Sum = %.2lf",sum);
return 0;
}
Output
This program calculates the sum of maximum of 10 numbers. It's because, when the user enters
negative number, the break statement is executed and loop is terminated.
The continue statement skips some statements inside the loop. The continue statement is used
with decision making statement such as if...else.
continue;
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a n10: 12
Sum = 59.70
In the program, when the user enters positive number, the sum is calculated using sum +=
number; statement.
When the user enters negative number, the continue statement is executed and skips the negative
number from calculation.
C switch...case Statement
The if..else..if ladder allows you to execute a block code among many alternatives. If you are
checking on the value of a single variable in if...else...if, it is better to use switchstatement.
The switch statement is often faster than nested if...else (not always). Also, the syntax of switch
statement is cleaner and easy to understand.
Syntax of switch...case
switch (n)
case constant1:
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
default:
When a case constant is found that matches the switch expression, control of the program passes
to the block of code associated with that case.
In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute
the block of code associate with the case statement until the end of switch block, or until the
break statement is encountered.
The break statement is used to prevent the code running into the next case.
switch Statement Flowchart
# include <stdio.h>
int main() {
char operator;
double firstNumber,secondNumber;
scanf("%c", &operator);
switch(operator)
case '+':
break;
case '-':
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber*secondNumber);
break;
case '/':
break;
default:
return 0;
Output
12.4
The - operator entered by the user is stored in operator variable. And, two operands 32.5 and
12.4 are stored in variables firstNumber and secondNumber respectively.
If break statement is not used, all cases after the correct case is executed.
Char
char alphabet;
const
const int a = 5;
Loops are used in programming to repeat a specific block until some end condition is met. There
are three loops in C programming:
1. for loop
2. while loop
3. do...while loop
while loop
while (testExpression)
//codes
}
where, testExpression checks the condition is true or false before each loop.
If the test expression is true (nonzero), codes inside the body of while loop are exectued. The test
expression is evaluated again. The process goes on until the test expression is false.
int main()
int number;
scanf("%d",&number);
factorial = 1;
--number;
return 0;
}
Output
Enter an integer: 5
Factorial = 120
do...while loop
The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed once, before checking the test expression. Hence, the do...while
loop is executed at least once.
do
{
// codes
}
while (testExpression);
The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the loop body is executed
again. This process goes on until the test expression is evaluated to 0 (false).
When the test expression is false (nonzero), the do...while loop is terminated.
Example #2: do...while loop
// Program to add numbers until user enters zero
#include <stdio.h>
int main()
{
double number, sum = 0;
return 0;
}
Output
Enter a number: 0
Sum = 4.70
Keywords double and float are used for declaring floating type variables. For example:
float number;
double longNumber;
Here, number is single precision floating type variable whereas, longNumber is a double
precision floating type variable.
C if statement
if (testExpression)
{
// statements
}
If the test expression is evaluated to true (nonzero), statements inside the body of if is executed.
If the test expression is evaluated to false (0), statements inside the body of if is skipped from
execution.
To learn more on when test expression is evaluated to nonzero (true) and 0 (false), check
out relational and logical operators.
Flowchart of if statement
Example #1: C if statement
// Program to display a number if user enters negative number
// If user enters positive number, that number won't be displayed
#include <stdio.h>
int main()
{
int number;
return 0;
}
Output 1
Enter an integer: -2
When user enters -2, the test expression (number < 0) becomes true. Hence, You entered -2 is
displayed on the screen.
Output 2
Enter an integer: 5
When user enters 5, the test expression (number < 0) becomes false and the statement inside the
body of if is skipped.
C if...else statement
The if...else statement executes some code if the test expression is true (nonzero) and some other
code if the test expression is false (0).
Syntax of if...else
if (testExpression)
{
// codes inside the body of if
}
else
{
// codes inside the body of else
}
If test expression is true, codes inside the body of if statement is executed and, codes inside the
body of else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes inside
the body of if statement is skipped.
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
When user enters 7, the test expression ( number%2 == 0 ) is evaluated to false. Hence, the
statement inside the body of else statement printf("%d is an odd integer"); is executed and the
statement inside the body of if is skipped.
The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.
Syntax of nested if...else statement.
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3
is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Output
23
Result: 12 < 23
enum
Enumeration types are declared in C programming using keyword enum. For example:
enum suit
hearts;
spades;
clubs;
diamonds;
};
Here, a enumerated variable suit is created having tags: hearts, spades, clubs and diamonds.
extern
The extern keyword declares that a variable or a function has external linkage outside of the file
it is declared.
Loops are used in programming to repeat a specific block until some end condition is met. There
are three loops in C programming:
1. for loop
2. while loop
3. do...while loop
for Loop
// codes
Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated.
But if the test expression is true (nonzero), codes inside the body of for loop is executed and the
update expression is updated.
This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.
To learn more on test expression (when test expression is evaluated to nonzero (true) and 0
(false)), check out relational and logical operators.
int main()
scanf("%d", &num);
sum += count;
return 0;
Output
Sum = 55
The value entered by the user is stored in variable num. Suppose, the user entered 10.
The count is initialized to 1 and the test expression is evaluated. Since, the test expression count
<= num (1 less than or equal to 10) is true, the body of for loop is executed and the value
of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2. Again, the test
expression is evaluated. Since, 2 is also less than 10, the test expression is evaluated to true and
the body of for loop is executed. Now, the sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11 the test expression is evaluated to 0 (false) as 11 is not less than or equal to
10. Therefore, the loop terminates and next, the total sum is printed.
C goto Statement
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
The label is an identifier. When goto statement is encountered, control of the program jumps
to label: and starts executing the code.
Example: goto Statement
// If user enters negative number, the sum and average of previously entered positive
number is displayed
# include <stdio.h>
int main()
int i;
scanf("%lf",&number);
goto jump;
jump:
average=sum/(i-1);
return 0;
Output
1. Enter a number: 3
Sum = 16.60
The use of goto statement may lead to code that is buggy and hard to follow. For example:
one:
{
test += i;
goto two;
two:
if (test > 5) {
goto three;
... .. ...
Also, goto statement allows you to do bad stuff such as jump out of scope.
That being said, goto statement can be useful sometimes. For example: to break from nested
loops.
If you think the use of goto statement simplifies your program. By all means use it. The goal here
is to create code that your fellow programmers can understand easily.
int
int count;
The short, long, signed and unsigned keywodrs are type modifiers that alters the meaning of a
base data type to yield a new type.
return
The return keyword terminates the function and returns the value.
int func()
int b = 5;
return b;
sizeof
#include <stdio.h>
int main()
printf("%u bytes.",sizeof(char));
Output
1 bytes.
register
The register keyword creates register variables which are much faster than normal variables.
The static keyword creates static variable. The value of the static variables persists until the end
of the program. For example:
struct
The struct keyword is used for declaring a structure. A structure can hold variables of different
types under a single name.
struct student{
char name[80];
float marks;
int age;
}s1, s2;
typedef
kg bear, tiger;
union
A Union is used for grouping different types of variable under a single name.
union student
char name[80];
float marks;
int age;
void
The void keyword indicates that a function doesn't return any value.
void testFunction(int a)
.....
Here, function testFunction( ) cannot return a value because the return type is void.
volatile
The volatile keyword is used for creating volatile objects. A volatile object can be modified in an
unspecified way by the hardware.
Since, number is a constant variable, the program cannot change it. However, hardware can
change it since it is a volatile object.
C Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifier must be unique. They are created to give unique name to a entity to identify it during
the execution of the program. For example:
int money;
double accountBalance;
Also remember, identifier names must be different from keywords. You cannot use int as an
identifier because int is a keyword.
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
2. The first letter of an identifier should be either a letter or an underscore. However, it is
discouraged to start an identifier name with an underscore.
3. There is no rule on length of an identifier. However, the first 31 characters of identifiers
are discriminated by the compiler.
Variables
To indicate the storage area, each variable should be given a unique name (identifier). Variable
names are just the symbolic representation of a memory location. For example:
Here, playerScore is a variable of integer type. The variable is assigned value: 95.
1. A variable name can have letters (both uppercase and lowercase letters), digits and
underscore only.
2. The first letter of a variable should be either a letter or an underscore. However, it is
discouraged to start variable name with an underscore. It is because variable name that
starts with an underscore can conflict with system name and may cause error.
3. There is no rule on how long a variable can be. However, only the first 31 characters of a
variable are checked by the compiler. So, the first 31 letters of two variables in a program
should be different.
C is a strongly typed language. What this means it that, the type of a variable cannot be changed.
Constants/Literals
A constant is a value or an identifier whose value cannot be altered in a program. For example: 1,
2.5, "C programming is easy", etc.
Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.
An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:
For example:
2. Floating-point constants
A floating point constant is a numeric constant that has either a fractional form or an exponent
form. For example:
-2.0
0.0000234
-0.22E-5
3. Character constants
A character constant is a constant which uses single quotation around characters. For example:
'a', 'l', 'm', 'F'
4. Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C
programming. For example: newline(enter), tab, question mark etc. In order to use these
characters, escape sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way the
characters are interpreted by the compiler.
Escape Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
Escape Sequences
\\ Backslash
\? Question mark
\0 Null character
5. String constants
String constants are the constants which are enclosed in a pair of double-quote marks. For
example:
6. Enumeration constants
Here, color is a variable and yellow, green, black and white are the enumeration constants having
value 0, 1, 2 and 3 respectively.
C Programming Enumeration
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements
during declaration (if necessary).
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};
When you create an enumerated type, only blueprint for the variable is created. Here's how you
can create variables of enum type.
enum boolean
false, true
} check;
int main()
{
enum week today;
today = wednesday;
printf("Day %d",today+1);
return 0;
}
Output
Day 4
Enum variable takes only one value out of many possible values. Example to demonstrate it,
#include <stdio.h>
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;
int main()
{
card = club;
printf("Size of enum variable = %d bytes", sizeof(card));
return 0;
}
Output
You can accomplish the same task using structures. However, working with enums gives you
efficiency along with flexibility.
How to use enums for flags?
enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4
} button;
Suppose you are designing a button for Windows application. You can set
flags ITALICS, BOLD and UNDERLINE to work with text.
There is a reason why all the integral constants are power of 2 in above pseudocode.
// In binary
ITALICS = 00000001
BOLD = 00000010
UNDERLINE = 00000100
Since, the integral constants are power of 2, you can combine two or more flags at once without
overlapping using bitwise OR | operator. This allows you to choose two or more flags at once.
For example,
#include <stdio.h>
enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4
};
int main() {
int myDesign = BOLD | UNDERLINE;
// 00000001
// | 00000100
// ___________
// 00000101
printf("%d", myDesign);
return 0;
}
Output
When the output is 5, you always know that bold and underline is used.
Also, you can add flag to your requirements.
Here, we have added italics to our design. Note, only code for italics is written inside if
statement.
Data types simply refers to the type and size of data associated with variables and functions.
Data types in C
Integer
Integers is the set of numbers that include all the whole numbers and their negative values.
The set of integers can be represented as - .... -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5.....
In programming, integer is a data type used to represent integer values. We can declare a variable
as an integer type or define the result of a function or expression as of integer type.
A variable defined as an integer type cannot store any other types of data such as character like
a,b,c or floating-point numbers like 5.43, -0.43.
int a = 5;
var a = 5;
o Floating type
Floating-point
Floating-point, as the name implies, are numbers that contain decimal points that can float left or
right.
In programming, floating-point is used to represent fractions. Numbers such as 1/2, 5/7, -100/3
can be represented in floating-point as 0.5, 0.71428, -33.33.
Often the keyword 'float' is used to declare a variable that stores floating-point numbers.
float pi = 3.14;
However, in other programming languages such as Javascript, Python we do need to specify the
datatype. Instead, we can just write,
o Character type
Character
A character can be any letter, number, punctuation marks, symbols or whitespace. For example,
the word "character" consists of eight characters, and the phrase "Hello World!" consists of 12
characters including the whitespace and exclamation mark.
C Programming Arrays
An array is a collection of data that holds fixed number of values of same type. For example: if
you want to store marks of 100 students, you can create an array for it.
float marks[100];
The size and type of arrays cannot be changed after its declaration.
1. One-dimensional arrays
2. Multidimensional arrays (will be discussed in next chapter)
data_type array_name[array_size];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5
floating-point values.
Suppose you declared an array mark as above. The first element is mark[0], second element
is mark[1] and so on.
Few key notes:
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
scanf("%d", &mark[2]);
scanf("%d", &mark[i]);
printf("%d", mark[0]);
printf("%d", mark[i-1]);
Example: C Arrays
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
int testArray[10];
If you try to access array elements outside of its bound, let's say testArray[12], the compiler may
not show any error. However, this may cause unexpected output (undefined behavior).
o Pointers
C Programming Pointers
Pointers are powerful features of C and (C++) programming that differentiates it from other
popular programming languages like: Java and Python.
Pointers are used in C program to access the memory and manipulate the address.
Address in C
Before you get into the concept of pointers, let's first get familiar with address in C.
If you have a variable var in your program, &var will give you its address in the memory,
where & is commonly called the reference operator.
You must have seen this notation while using scanf() function. It was used in the function to
store the user inputted value in the address of var.
scanf("%d", &var);
Output
Value: 5
Address: 2686778
Note: You may obtain different value of address while using this code.
In above source code, value 5 is stored in the memory location 2686778. var is just the name
given to that location.
Pointer variables
In C, there is a special variable that stores just the address of another variable. It is called Pointer
variable or, simply, a pointer.
Declaration of Pointer
data_type* pointer_variable_name;
int* p;
As discussed, & is called reference operator. It gives you the address of a variable.
Likewise, there is another operator that gets you the value from the address, it is called a
dereference operator (*).
Below example clearly demonstrates the use of pointers, reference operator and dereference
operator.
Note: The * sign when declaring a pointer is not a dereference operator. It is just a similar
notation that creates a pointer.
Output
Address of c: 2686784
Value of c: 22
Address of c: 2686784
Value of c: 2
int c, *pc;
o Structures
C Programming Structure
For example: You want to store some information about a person: his/her name, citizenship
number and salary. You can easily create different variables name, citNo, salary to store this
information separately.
However, in the future, you would want to store information about multiple persons. Now, you'd
need to create different variables for each information per person: name1, citNo1, salary1,
name2, citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no relation
between the variables (information) would exist, it's going to be a daunting task.
A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner, readable and
efficient as well.
This collection of all related information under a single name Person is a structure.
Structure Definition in C
struct structure_name
data_type member1;
data_type member2;
data_type memeber;
};
struct person
char name[50];
int citNo;
float salary;
};
This declaration above creates the derived data type struct person.
Structure variable declaration
When a structure is defined, it creates a user-defined type but, no storage or memory is allocated.
struct person
char name[50];
int citNo;
float salary;
};
int main()
return 0;
struct person
char name[50];
int citNo;
float salary;
In both cases, two variables person1, person2 and an array person3 having 20 elements of
type struct person are created.
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->) (is discussed in structure and pointers tutorial)
structure_variable_name.member_name
Suppose, we want to access salary for variable person2. Then, it can be accessed as:
person2.salary
Example of structure
Write a C program to add two distances entered by user. Measurement of distance should
be in inch and feet. (Note: 12 inches = 1 foot)
Output
1st distance
Enter feet: 12
2nd distance
Enter feet: 2
Enter inch: 9.8
So, developers generally use typedef to name the structure as a whole. For example:
int imag;
float real;
} comp;
int main()
Here, typedef keyword is used in creating a type comp (which is of type as struct complex).
Then, two structure variables comp1 and comp2 are created by this comp type.
int imag_value;
float real_value;
};
struct number
int real;
} num1, num2;
Suppose, you want to access imag_value for num2 structure variable then, following structure
member is used.
num2.comp.imag_value
1. Passing by value
2. Passing by reference
o Enumeration
int - Integer data types
Integers are whole numbers that can have both positive and negative values but no decimal
values. Example: 0, -5, 10
In C programming, keyword int is used for declaring integer variable. For example:
int id;
The size of int is either 2 bytes(In older PC's) or 4 bytes. If you consider an integer having size of
4 byte( equal to 32 bits), it can take 232 distinct states as: -231,-231+1, ...,-2, -1, 0, 1, 2, ..., 231-2,
231-1. If you try to store larger number than 231-1, i.e,+2147483647 and smaller number than -
231, i.e, -2147483648, program will not run correctly.
Similarly, int of 2 bytes, it can take 216 distinct states from -215 to 215-1.
Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc. You can declare a
floating point variable in C by using either float or double keyword. For example:
float accountBalance;
double bookPrice;
The size of float (single precision float data type) is 4 bytes. And the size of double (double
precision float data type) is 8 bytes. Floating point variables has a precision of 6 digits whereas
the precision of double is 14 digits.
Keyword char is used for declaring character type variables. For example:
C Qualifiers
Qualifiers alters the meaning of base data types to yield a new data type.
Size qualifiers
Size qualifiers alters the size of a basic type. There are two size qualifiers, long and short. For
example:
long double i;
The size of double is 8 bytes. However, when long keyword is used, that variable becomes 10
bytes.
There is another keyword short which can be used if you previously know the value of a variable
will always be a small number.
Sign qualifiers
Integers and floating point variables can hold both negative and positive values. However, if a
variable needs to hold positive value only, unsigned data types are used. For example:
An integer variable of 4 bytes can hold data from -231 to 231-1. However, if the variable is
defined as unsigned, it can hold data from 0 to 232-1.
It is important to note that, sign qualifiers can be applied to int and char types only.
Constant qualifiers
Volatile qualifiers
A variable should be declared volatile whenever its value can be changed by some external
sources outside the program. Keyword volatile is used for creating volatile variables.
C programming has several in-built library functions to perform input and output tasks.
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scanf() function reads formatted input from standard input (keyboard) whereas
the printf() function sends formatted output to the standard output (screen).
Output
C Programming
How this program works?
All valid C program must contain the main() function. The code execution begins from
the start of main() function.
The printf() is a library function to send formatted output to the screen.
The printf()function is declared in "stdio.h" header file.
Here, stdio.h is a header file (standard input output header file) and #include is a
preprocessor directive to paste the code from the header file when necessary. When the
compiler encounters printf() function and doesn't find stdio.h header file, compiler shows
error.
The return 0; statement is the "Exit status" of the program. In simple terms, program
ends.
Output
Number = 5
Inside the quotation of printf() function, there is a format string "%d" (for integer). If the format
string matches the argument (testInteger in this case), it is displayed on the screen.
Enter an integer: 4
Number = 4
The scanf() function reads formatted input from the keyboard. When user enters an integer, it is
stored in variable testInteger.
Note the '&' sign before testInteger; &testInteger gets the address of testInteger and the value is
stored in that address.
Output
Value = 23.450000
The format string "%f" is used to read and display formatted in case of floats.
Output
Enter a character: g
You entered g.
When a character is entered in the above program, the character itself is not stored. Instead, a
numeric value(ASCII value) is stored.
And when we displayed that value using "%c" text format, the entered character is displayed.
Enter a character: g
You entered g.
The ASCII value of character 'g' is 103. When, 'g' is entered, 103 is stored in variable var1
instead of g.
You can display a character if you know ASCII code of that character. This is shown by
following example.
Output
// Tries to print number right justified to 3 digits but the number is not right adjusted because
there are only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);
Output
C Programming Operators
An operator is a symbol which operates on a value or a variable. For example: + is an operator to
perform addition.
C programming has wide range of operators to perform various operations. For better
understanding of operators, these operators can be classified as:
Operators in C programming
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
C Arithmetic Operators
* multiplication
/ division
Operator Meaning of Operator
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
The operators +, - and * computes addition, subtraction and multiplication respectively as you
might have expected.
It is because both variables a and b are integers. Hence, the output is also an integer. The
compiler neglects the term after decimal point and shows answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder
is 1. The % operator can only be used with integers.
C programming has two operators increment ++ and decrement -- to change the value of an
operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate on a single operand.
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
Here, the operators ++ and -- are used as prefix. These two operators can also be used as postfix
like a++ and a--. Visit this page to learn more on how increment and decrement operators work
when used as postfix.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =
Operator Example Same as
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
c = a;
printf("c = %d \n", c);
c += a; // c = c+a
printf("c = %d \n", c);
c -= a; // c = c-a
printf("c = %d \n", c);
c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
C Relational Operators
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
== Equal to 5 == 3 returns 0
return 0;
Output
5 == 5 = 1
5 == 10 = 0
5>5=0
5 > 10 = 0
5<5=0
5 < 10 = 1
5 != 5 = 0
5 != 10 = 1
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1
C Logical Operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Output
(a == b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0
Bitwise Operators
During computation, mathematical operations like: addition, subtraction, addition and division
are converted to bit-level which makes processing faster and saves power.
| Bitwise OR
Operators Meaning of operators
^ Bitwise exclusive OR
~ Bitwise complement
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof is an unary operator which returns the size of data (constant, variables, array, structure
etc).
Output
Output
C Programming Functions
Suppose, a program related to graphics needs to create a circle and color it depending upon the
radius and color from the user. You can create two functions to solve this problem:
Dividing complex problem into small components makes program easy to understand and use.
Depending on whether a function is defined by the user or already included in C compilers, there
are two types of functions in C programming
The standard library functions are built-in functions in C programming to handle tasks such as
mathematical computations, I/O processing, string handling etc.
These functions are defined in the header file. When you include the header file, these functions
are available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display output
on the screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these functions
are available for use.
Visit this page to learn more about standard library functions in C programming.
User-defined functions
As mentioned earlier, C allow programmers to define functions. Such functions created by the
user are called user-defined functions.
Depending upon the complexity and requirement of the program, you can create as many user-
defined functions as you want.
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
When the compiler encounters functionName(); inside the main function, control of the program
jumps to
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside
the function definition are executed.
This is just an overview on user-defined function. Visit these pages to learn more on:
C allows you to define functions according to your need. These functions are known as user-
defined functions. For example:
Suppose, you need to create a circle and color it depending upon the radius and color. You can
create two functions to solve this problem:
createCircle() function
color() function
#include <stdio.h>
int main()
{
int n1,n2,sum;
printf("sum = %d",sum);
return 0;
}
Function prototype
A function prototype is simply the declaration of a function that specifies function's name,
parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used in the
program.
In the above example, int addNumbers(int a, int b); is the function prototype which provides
following information to the compiler:
The function prototype is not needed if the user-defined function is defined before
the main() function.
Calling a function
In the above example, function call is made using addNumbers(n1,n2); statement inside
the main().
Function definition
Function definition contains the block of code to perform a specific task i.e. in this case, adding
two numbers and returning it.
When a function is called, the control of the program is transferred to the function definition.
And, the compiler starts executing the codes inside the body of a function.
Passing arguments to a function
In programming, argument refers to the variable passed to the function. In the above example,
two variables n1 and n2 are passed during function call.
The parameters a and b accepts the passed arguments in the function definition. These arguments
are called formal parameters of the function.
The type of arguments passed to a function and the formal parameters must match, otherwise the
compiler throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be
of float type.
Return Statement
The return statement terminates the execution of a function and returns a value to the calling
function. The program control is transferred to the calling function after return statement.
In the above example, the value of variable result is returned to the variable sum in
the main() function.
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type specified in function prototype
and function definition must match.
For better understanding of arguments and return value from the function, user-defined
functions can be categorized as:
The 4 programs below check whether an integer entered by the user is a prime number or not.
And, all these programs generate the same output.
void checkPrimeNumber();
int main()
{
checkPrimeNumber(); // no argument is passed to prime()
return 0;
}
// return type of the function is void becuase no value is returned from the function
void checkPrimeNumber()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
The checkPrimeNumber() function takes input from the user, checks whether it is a prime
number or not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside the main() function indicates
that no argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.
int main()
{
int n, i, flag = 0;
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
return n;
}
The empty parentheses in n = getInteger(); statement indicates that no argument is passed to the
function. And, the value returned from the function is assigned to n.
Here, the getInteger() function takes input from the user and returns it. The code to check
whether a number is prime or not is inside the main() function.
return 0;
}
Here, the checkPrimeAndDisplay() function checks whether the argument passed is a prime
number or not and displays the appropriate message.
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
return 0;
}
The checkPrimeNumber() function checks whether the passed argument is prime or not. If the
passed argument is a prime number, the function returns 0. If the passed argument is a non-prime
number, the function returns 1. The return value is assigned to flag variable.
Then, the appropriate message is displayed from the main() function.
Well, it depends on the problem you are trying to solve. In case of this problem, the last
approach is better.
A function should perform a specific task. The checkPrimeNumber() function doesn't take input
from the user nor it displays the appropriate message. It only checks whether a number is prime
or not, which makes code modular, easy to understand and debug.
C Programming Recursion
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
The recursion continues until some condition is met to prevent it.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and other doesn't.
#include <stdio.h>
int main()
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
if (num!=0)
else
return num;
}
Output
Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of num is 3 initially. During next function call, 2 is passed to
the sum()function. This process continues until num is equal to 0.
When num is equal to 0, the if condition fails and the else part is executed returning the sum of
integers to the main() function.
Advantages and Disadvantages of Recursion
Recursion makes program elegant and cleaner. All algorithms can be defined recursively which
makes it easier to visualize and prove.
If the speed of the program is vital then, you should avoid using recursion. Recursions use more
memory and are generally slow. Instead, you can use loop.
TURBO C++
C++ Functions
In programming, function refers to a segment that groups code to perform a specific task.
Depending on whether a function is predefined or created by programmer; there are two types of
function:
1. Library Function
2. User-defined Function
Library Function
Programmer can use library function by invoking function directly; they don't need to write it
themselves.
#include <iostream>
#include <cmath>
int main()
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
Output
Enter a number: 26
In the example above, sqrt() library function is invoked to calculate the square root of a number.
Notice code #include <cmath> in the above program. Here, cmath is a header file. The function
definition of sqrt()(body of that function) is present in the cmath header file.
You can use all functions defined in cmath when you include the content of file cmath in this
program using #include <cmath> .
Every valid C++ program has at least one function, that is, main() function.
User-defined Function
A user-defined function groups code to perform a specific task and that group of code is given a
name(identifier).
When the function is invoked from any part of program, it all executes the codes defined in the
body of function.
When a program begins running, the system calls the main() function, that is, the system starts
executing codes from main() function.
When control of the program reaches to function_name() inside main(), it moves to void
function_name() and all codes inside void function_name() is executed.
Then, control of the program moves back to the main function where the code after the call to
the function_name() is executed as shown in figure above.
C++ program to add two integers. Make a function add() to add integers and display sum
in main() function.
#include <iostream>
int main()
// Function call
return 0;
// Function definition
int add;
add = a + b;
// Return statement
return add;
Output
-4
Sum = 4
Function prototype (declaration)
If a user-defined function is defined after main() function, compiler will show error. It is because
compiler is unaware of user-defined function, types of argument passed to function and return
type.
In C++, function prototype is a declaration of function without its body to give compiler
information about user-defined function. Function prototype in the above example is:
You can see that, there is no body of function in prototype. Also, there are only return type of
arguments but no arguments. You can also declare function prototype as below but it's not
necessary to write arguments.
Function Call
To execute the codes of function body, the user-defined function needs to be invoked(called).
In the above program, add(num1,num2); inside main() function calls the user-defined function.
Function Definition
The function itself is referred as function definition. Function definition in the above program is:
// Function definition
{
int add;
add = a + b;
return add;
When the function is called, control is transferred to the first statement of the function body.
When all codes inside function definition is executed, control of program moves to the calling
program.
In programming, argument (parameter) refers to the data which is passed to a function (function
definition) while calling it.
In the above example, two variables, num1 and num2 are passed to function during function call.
These arguments are known as actual arguments.
The value of num1 and num2 are initialized to variables a and b respectively. These
arguments a and b are called formal arguments.
The numbers of actual arguments and formals argument should be the same.
(Exception: Function Overloading)
The type of first actual argument should match the type of first formal argument.
Similarly, type of second actual argument should match the type of second formal
argument and so on.
You may call function a without passing any argument. The number(s) of argument
passed to a function depends on how programmer want to solve the problem.
You may assign default values to the argument. These arguments are known as default
arguments.
In the above program, both arguments are of int type. But it's not necessary to have both
arguments of same type.
Return Statement
A function can return a single value to the calling program using return statement.
In the above program, the value of add is returned from user-defined function to the calling
program using statement below:
return add;
Notice that the variable returned, i.e., add is of type int and sum is also of int type.
Also, notice that the return type of a function is defined in function declarator int add(int a, int
b). The int before add(int a, int b) means the function should return a value of type int.
For better understanding of arguments and return in functions, user-defined functions can be
categorised as:
Consider a situation in which you have to check prime number. This problem is solved below by
making user-defined function in 4 different ways as mentioned above.
void prime();
int main()
{
// No argument is passed to prime()
prime();
return 0;
}
if (flag == 1)
{
cout << num << " is not a prime number.";
}
else
{
cout << num << " is a prime number.";
}
}
In the above program, prime() is called from the main() with no arguments.
prime() takes the positive number from the user and checks whether the number is a prime
number or not.
Since, return type of prime() is void, no value is returned from the function.
int prime();
int main()
{
int num, i, flag = 0;
if (flag == 1)
{
cout<<num<<" is not a prime number.";
}
else
{
cout<<num<<" is a prime number.";
}
return 0;
}
return n;
}
In the above program, prime() function is called from the main() with no arguments.
prime() takes a positive integer from the user. Since, return type of the function is an int, it
returns the inputted number from the user back to the calling main() function.
Then, whether the number is prime or not is checked in the main() itself and printed onto the
screen.
int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;
// There is no return value to calling function. Hence, return type of function is void. */
void prime(int n)
{
int i, flag = 0;
for (i = 2; i <= n/2; ++i)
{
if (n%i == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
cout << n << " is not a prime number.";
}
else {
cout << n << " is a prime number.";
}
}
In the above program, positive number is first asked from the user which is stored in the
variable num.
Then, num is passed to the prime() function where, whether the number is prime or not is
checked and printed.
Since, the return type of prime() is a void, no value is returned from the function.
int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;
if(flag == 1)
cout << num << " is not a prime number.";
else
cout<< num << " is a prime number.";
return 0;
}
return 0;
}
In the above program, a positive integer is asked from the user and stored in the variable num.
Then, num is passed to the function prime() where, whether the number is prime or not is
checked.
Since, the return type of prime() is an int, 1 or 0 is returned to the main() calling function. If the
number is a prime number, 1 is returned. If not, 0 is returned.
Back in the main() function, the returned 1 or 0 is stored in the variable flag, and the
corresponding text is printed onto the screen.
In C++ programming, two functions can have same name if number and/or type of arguments
passed are different.
These functions having different number or type (or both) of parameters are known as
overloaded functions. For example:
int test() { }
int test(int a) { }
float test(double a) { }
Here, all 4 functions are overloaded functions because argument(s) passed to these functions are
different.
Notice that, the return type of all these 4 functions are not same. Overloaded functions may or
may not have different return type but it should have different argument(s).
// Error code
int test(int a) { }
The number and type of arguments passed to these two functions are same even though the
return type is different. Hence, the compiler will throw error.
void display(int);
void display(float);
void display(int, float);
int main() {
int a = 5;
float b = 5.5;
display(a);
display(b);
display(a, b);
return 0;
}
Output
Integer number: 5
Here, the display() function is called three times with different type or number of arguments.
The return type of all these functions are same but it's not necessary.
#include <iostream>
using namespace std;
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;
cout << "Absolute value of " << a << " = " << absolute(a) << endl;
cout << "Absolute value of " << b << " = " << absolute(b);
return 0;
}
Output
Absolute value of -5 = 5
Both functions take single argument. However, one function takes integer as an argument and
other takes float as an argument.
When absolute() function is called with integer as an argument, this function is called:
In C++ programming, you can provide default values for function parameters.
The idea behind default argument is simple. If a function is called by passing argument/s, those
arguments are used by the function.
But if the argument/s are not passed while invoking a function then, the default values are used.
#include <iostream>
int main()
display();
display('#');
cout << "\nBoth argument passed:\n";
display('$', 5);
return 0;
cout << c;
Output
No argument passed:
In the above program, you can see the default value assigned to the arguments void display(char
= '*', int = 1);.
Then, only the first argument is passed using the function second time. In this case, function does
not use first default value passed. It uses the actual parameter passed as the first argument c =
# and takes default value n = 1 as its second argument.
When display() is invoked for the third time passing both arguments, default arguments are not
used. So, the value of c = $ and n = 5.
The above function will not compile. You cannot miss a default argument in between two
arguments.
In this case, c should also be assigned a default value.
The above function will not compile as well. You must provide default values for each
argument after b.
In this case, c and d should also be assigned default values.
If you want a single default argument, make sure the argument is the last one. void
add(int a, int b, int c, int d = 4);
3. No matter how you use default arguments, a function should always be written so that it
serves only one purpose.
If your function does more than one thing or the logic seems too complicated, you can
use Function overloading to separate the logic better.
Every variable in C++ has two features: type and storage class.
Type specifies the type of data that can be stored in a variable. For example: int, float, char etc.
And, storage class controls two different properties of a variable: lifetime (determines how long
a variable can exist) and scope (determines which part of the program can access it).
Depending upon the storage class of a variable, it can be divided into 4 major types:
Local variable
Global variable
Static local variable
Register Variable
Thread Local Storage
Local Variable
A variable defined inside a function (defined inside function body between braces) is called a
local variable or automatic variable.
Its scope is only limited to the function where it is defined. In simple terms, local variable exists
and can be accessed only inside a function.
The life of a local variable ends (It is destroyed) when the function exits.
void test();
int main()
{
// local variable to main()
int var = 5;
test();
void test()
{
// local variable to test()
int var1;
var1 = 6;
The variable var cannot be used inside test() and var1 cannot be used inside main()function.
Keyword auto was also used for defining local variables before as: auto int var;
But, after C++11 auto has a different meaning and should not be used for defining local
variables.
Global Variable
The scope of a global variable is the whole program. This means, It can be used and changed at
any part of the program after its declaration.
void test();
int main()
{
++c;
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test()
{
++c;
// Outputs 14
cout << c;
}
Output
13
14
This variable is visible to both functions main() and test() in the above program.
... .. ...
int main()
{
static float a;
... .. ...
A static local variable exists only inside a function where it is declared (similar to a local
variable) but its lifetime starts when the function is called and ends only when the program ends.
The main difference between local variable and static variable is that, the value of static variable
persists the end of the program.
void test()
{
// var is a static variable
static int var = 0;
++var;
int main()
{
test();
test();
return 0;
}
Output
During the first call, variable var is declared as static variable and initialized to 0. Then 1 is
added to var which is displayed in the screen.
When the function test() returns, variable var still exists because it is a static variable.
During second function call, no new variable var is created. The same var is increased by 1 and
then displayed to the screen.
Register variables are similar to automatic variables and exists inside a particular function only.
It is supposed to be faster than the local variables.
If a program encounters a register variable, it stores the variable in processor's register rather
than memory if available. This makes it faster than the local variables.
However, this keyword was deprecated in C++11 and should not be used.
Thread Local Storage
Thread-local storage is a mechanism by which variables are allocated such that there is one
instance of the variable per extant thread.
Global data, while usually considered poor design, nevertheless often is a useful means to
preserve state between related function calls. When it comes to using threads, the issue
unfortuantely is complicated by the fact that some access synchronisation is needed, to avoid that
more than one thread will modify the data.
There are times when you will want to have a globally visible object, while still having the data
content accessible only to the calling thread, without holding off other threads that contend for
the "same" global object. This is where thread local storage (TLS) comes in. TLS is something
the operating system / threading subsystem provides, and by its very nature is rather low level.
From a globally visible object (in C++) you expect that its constructors are getting called before
you enter "main", and that it is disposed properly, after you exit from "main". Consequently one
would expect a thread local "global" object beeing constructed, when a thread starts up, and
beeing destroyed when the thread exits. But this is not the case! Using the native API one can
only have TLS that needs neither code to construct nor code to destruct.
While at first glance this is somewhat disappointing, there are reasons, not to automatically
instantiate all these objects on every thread creation. A clean solution to this problem is
presented e.g. in the "boost" library. Also the standard "pthread" C library addresses this problem
properly. But when you need to use the native windows threading API, or need to write a library
that, while making use of TLS, has no control over the threading API the client code is using,
you are apparently lost.
Fortunately this is not true, and this is the topic of this article. The Windows Portable Executable
(PE) format provides for support of TLS-Callbacks. Altough the documentation is hard to read,
it can be done with current compilers i.e. MSVC 6.0,7.1,... Since noone else seemingly was using
this feature before, and not even the C runtime library (CRT) is making use of it, you should be a
little careful and watch out for undesired behaviour. Having said, that the CRT does not use it,
does not mean it does not implement it. Unfortunately there is a small bug present in the MSVC
6.0 implementation, that is also worked-around by my code.
If it turns out, that the concepts, presented in this article, prove to be workable in "real life", I
would be glad if this article has helped to remove some dust from this topic and make it usable
for a broader range of applications. I could e.g. think of a generalized atexit_thread function that
makes use of the concepts presented here.
Before going to explain the gory details, I want to mention Aaron W. LaFramboise who made
me aware of the existence of the TLS-Callback mechanism.
If you are using the precompiled binaries, you simply will need to copy the *.lib files to a
convenient directory where your compiler usually will find libraries. So you will copy the files
from the include directory to a directory where your compiler searches for includes.
Alternatively you may simply copy the files to your project directory.
The following is a simple demonstration of usage, to get you started.
#include <process.h>
// first include the header file
#include <tls.h>
While at first glance it might appear natural that the tls-objects should not be wrapped as
pointers, in fact it is not. While the objects are globally visible, they are still "delegates" that
forward to a thread local copy. The natural way in C++ to express delegation is a pointer object.
(The technical reason of course is, that you cannot overload the "." operator but "->" can be
overloaded.)
You can use this mechanism when building a "*.exe" file of course, but you also can use it when
building a "*.dll" image. However when you are planning to load your DLL
by LoadLibary() you should define the macro TLS_ALLOC when building your DLL. This is
not necessary when using your DLL by means of an import library. A similar restriction applies
when delay-loading your DLL. Please consult your compiler documentation when you are
interested in the reasons for this. (Defining TLS_ALLOC forces the use of the TlsAlloc() family
functions from the Win32 API.)
Please again note, that it is not necessary to explicitely call the destructors of your class
(or release()). This is very handy, when you are writing a piece of code, that has no control over
the calling threads, but must still be multithread safe. One caveat however: The destructors of
your class are called _after_ the CRT code has ended the thread. Consequently when you are
doing something fancy in your destructors, which causes the CRT to reallocate its internal thread
local storage pointers, you will be left with a small memory leak of the CRT. This is comparable
in effect to the case when you are using the native Win32 API functions to create a thread,
instead of _beginthread().
In principle that is all you need. But wait! I mentioned a small bug in the version 6 of the
compiler. Luckily it is easy to work around. I provided an include file tlsfix.h which you will
need to include into your program. You need to make sure it is getting included
before windows.h. To be more precise: the TLS library must be searched before the default CRT
library. So you alternatively may specify the library on the command line on the first place, and
omit the inclusion of tlsfix.h.
Background
I will not discuss the user interface in this place. It suffices to say, that it essentialy is the same as
in the boost library. However I omitted the feature of beeing able to specify arbitrary deleter
functions, since this would have raised the need to include the boost library in my code. I wanted
to keep it small and just demonstrate the principles. However, my implementation also deviates
from boost insofar as I am featuring native compiler support for TLS variables, thus gaining an
almost 4 times speed improvement. No need to say, that my implementation of course is
Windows specific.
When thinking about TLS for C++ the main question is how to run the constructors and
destructors. A careful study of the PE format (e.g. in the MSDN library) reveals, that it almost
ever provided for TLS support. (Thanks again to Aaron W. LaFramboise who read it carefully
enough.) Of special interest is the section about TLS-Callback:
The program can provide one or more TLS callback functions (though Microsoft
compilers do not currently use this feature) to support additional
initialization and termination for TLS data objects. A typical reason to use
such a callback function would be to call constructors and destructors for
objects.
Well it is true, that the compilers do not use the feature, but there is nothing that prevents user
code to use it though. One somehow must convince the compiler (to be honest it is the linker) to
place your callback in a manner, so the operating system will call it. It turns out, that this is
surprisingly simple (omitting the deatils for a moment).
You can even add more callbacks, by appending pointers to the ".CRT$XLB" segment. The
fancy definitions are available from the windows.h and winnt.h include files in turn.
Now about the details: You will find at times, that your callbacks are not getting called. The
reason for this is when the linker does not correctly wire up your segments. It turns out, that this
coincides with when you are not using any __declspec(thread) in your code. A further study of
the PE format description reveals:
The Microsoft run-time library facilitates this process by defining a memory image of the TLS
Directory and giving it the special name __tls_used (Intel x86 platforms) or _tls_used
(other platforms). The linker looks for this memory image and uses the data there to create the
TLS Directory. Other compilers that support TLS and work with the Microsoft linker must use
this same technique.
C++ Recursion
A function that calls itself is known as recursive function. And, this technique is known as
recursion.
void recurse()
... .. ...
recurse();
... .. ...
int main()
... .. ...
recurse();
... .. ...
The figure below shows how recursion works by calling itself over and over again.
The recursion continues until some condition is met.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and other doesn't.
// Factorial of n = 1*2*3*...*n
#include <iostream>
int factorial(int);
int main()
{
int n;
cin >> n;
return 0;
int factorial(int n)
if (n > 1)
return n*factorial(n-1);
else
return 1;
Output
Factorial of 4 = 24
Explanation: How this example works?
1. In the first factorial() function, test expression inside if statement is true. The return
num*factorial(num-1); statement is executed, which calls the second factorial() function
and argument passed is num-1which is 3.
2. In the second factorial() function, test expression inside if statement is true. The return
num*factorial(num-1); statement is executed, which calls the third factorial()function and
argument passed is num-1 which is 2.
3. In the third factorial() function, test expression inside if statement is true. The return
num*factorial(num-1); statement is executed, which calls the fourth factorial() function
and argument passed is num-1 which is 1.
4. In the fourth factorial() function, test expression inside if statement is false. The return
1; statement is executed, which returns 1 to third factorial() function.
5. The third factorial() function returns 2 to the second factorial() function.
7. Finally, the first factorial() function returns 24 to the main() function, which is displayed
on the screen.
C++ Structures
Structure is a collection of variables of different data types under a single name. It is similar to
a class in that, both holds a collecion of data of different data types.
For example: You want to store some information about a person: his/her name, citizenship
number and salary. You can easily create different variables name, citNo, salary to store these
information separately.
However, in the future, you would want to store information about multiple persons. Now, you'd
need to create different variables for each information per person: name1, citNo1, salary1,
name2, citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no relation
between the variables (information) would exist, it's going to be a daunting task.
A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner, readable and
efficient as well.
This collection of all related information under a single name Person is a structure.
The struct keyword defines a structure type followed by an identifier (name of the structure).
Then inside the curly braces, you can declare one or more members (declare variables inside
curly braces) of that structure. For example:
struct Person
char name[50];
int age;
float salary;
};
Here a structure person is defined which has three members: name, age and salary.
The structure definition is only the blueprint for the creating of variables. You can imagine it as a
datatype. When you define an integer as below:
int foo;
The int specifies that, variable foo can hold integer element only. Similarly, structure definition
only specifies that, what property a structure variable holds when it is defined.
Once you declare a structure person as above. You can define a structure variable as:
Person bill;
When structure variable is defined, only then the required memory is allocated by the compiler.
Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes, memory
of int is 4 bytes and memory of char is 1 byte.
bill.age = 50;
C++ Program to assign data to members of a structure variable and display it.
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p1;
return 0;
}
Output
Enter age: 27
Displaying Information.
Age: 27
Salary: 1024.4
Here a structure Person is declared which has three members name, age and salary.
Inside main() function, a structure variable p1 is defined. Then, the user is asked to enter
information and data entered by user is displayed.
Structure variables can be passed to a function and returned in a similar way as normal
arguments.
A structure variable can be passed to a function in similar way as normal argument. Consider this
example:
Example 1: C++ Structure and Function
#include <iostream>
struct Person
char name[50];
int age;
float salary;
};
int main()
Person p;
cin.get(p.name, 50);
displayData(p);
return 0;
void displayData(Person p)
Output
Enter age: 55
Displaying Information.
Age: 55
Salary: 34233.4
In this program, user is asked to enter the name, age and salary of a Person
inside main()function.
The return type of displayData() is void and a single argument of type structure Person is passed.
#include <iostream>
struct Person {
char name[50];
int age;
float salary;
};
Person getData(Person);
void displayData(Person);
int main()
Person p;
p = getData(p);
displayData(p);
return 0;
Person getData(Person p) {
cin.get(p.name, 50);
return p;
void displayData(Person p)
In this program, the structure variable p of type structure Person is defined under main()function.
The structure variable p is passed to getData() function which takes input from user which is then
returned to main function.
p = getData(p);
Note: The value of all members of a structure variable can be assigned to another structure using
assignment operator = if both structure variables are of same type. You don't need to manually
assign each members.
Then the structure variable p is passed to displayData() function, which displays the information.
C++ Enumeration
By default, spring is 0, summer is 1 and so on. You can change the default value of an enum
element during declaration (if necessary).
enum season
{ spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
Enumerated Type Declaration
When you create an enumerated type, only blueprint for the variable is created. Here's how you
can create variables of enum type.
// inside function
Here is another way to declare same check variable using different syntax.
enum boolean
false, true
} check;
int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}
Output
Day 4
int main() {
seasons s;
s = summer;
cout << "Summer = " << s << endl;
return 0;
}
Output
Summer = 4
#include <iostream>
using namespace std;
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;
int main()
{
card = club;
cout << "Size of enum variable " << sizeof(card) << " bytes.";
return 0;
}
Output
You can accomplish the same task using C++ structures. However, working with enums gives
you efficiency along with flexibility.
enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4
} button;
Suppose you are designing a button for Windows application. You can set
flags ITALICS, BOLD and UNDERLINE to work with text.
There is a reason why all the integral constants are power of 2 in above pseudocode.
// In binary
ITALICS = 00000001
BOLD = 00000010
UNDERLINE = 00000100
Since, the integral constants are power of 2, you can combine two or more flags at once without
overlapping using bitwise OR | operator. This allows you to choose two or more flags at once.
For example,
#include <iostream>
using namespace std;
enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4
};
int main()
{
int myDesign = BOLD | UNDERLINE;
// 00000001
// | 00000100
// ___________
// 00000101
return 0;
}
Output
When the output is 5, you always know that bold and underline is used.
Here, we have added italics to our design. Note, only code for italics is written inside the if
statement.
You can accomplish almost anything in C++ programming without using enumerations.
However, they can be pretty handy in certain situations. That's what differentiates good
programmers from great programmers.
if Statement
if...else Statement
Conditional Operator
C++ if Statement
if (testExpression)
// statements
#include <iostream>
int main()
int number;
if ( number > 0)
cout << "You entered a positive integer: " << number << endl;
return 0;
Output 1
Enter an integer: 5
Output 2
Enter a number: -5
C++ if...else
The if else executes the codes inside the body of if statement if the test expression is true and
skips the codes inside the body of else.
If the test expression is false, it executes the codes inside the body of else statement and skips the
codes inside the body of if.
Flowchart of if...else
Example 2: C++ if...else Statement
// Program to check whether an integer is positive or negative
#include <iostream>
int main()
int number;
cout << "You entered a positive integer: " << number << endl;
else
cout << "You entered a negative integer: " << number << endl;
return 0;
Output
Enter an integer: -4
The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.
Syntax of Nested if...else
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3
is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
else if (number < 0)
{
cout<<"You entered a negative integer: " << number << endl;
}
else
{
cout << "You entered 0." << endl;
}
Output
Enter an integer: 0
You entered 0.
Conditional/Ternary Operator ?:
if ( a < b ) {
a = b;
else {
a = -b;
a = (a < b) ? b : -b;
The ternary operator is more readable than a if...else statement for short conditions.
1. for loop
2. while loop
3. do...while loop
// codes
// Factorial on n = 1*2*3*...*n
#include <iostream>
int main()
int i, n, factorial = 1;
cout << "Enter a positive integer: ";
cin >> n;
return 0;
Output
Factorial of 5 = 120
In the program, user is asked to enter a positive integer which is stored in variable n(suppose user
entered 5). Here is the working of for loop:
In the above program, variable i is not used outside of the for loop. In such cases, it is better to
declare the variable in for loop (at initialization statement).
#include <iostream>
int main()
int n, factorial = 1;
cin >> n;
return 0;
}
C++ while and do...while Loop
In computer programming, loop repeats a certain block of code until some end condition is met.
for Loop
while Loop
do...while Loop
while (testExpression)
// codes
// Factorial of n = 1*2*3...*n
#include <iostream>
int main()
++i;
return 0;
Output
Factorial of 4 = 24
In this program, user is asked to enter a positive integer which is stored in variable number. Let's
suppose, user entered 4.
Then, the while loop starts executing the code. Here's how while loop works:
The do...while loop is a variant of the while loop with one important difference. The body of
do...while loop is executed once before the test expression is checked.
do {
// codes;
while (testExpression);
The codes inside the body of loop is executed at least once. Then, only the test expression
is checked.
If the test expression is true, the body of loop is executed. This process continues until the
test expression becomes false.
When the test expression is false, do...while loop is terminated.
#include <iostream>
int main()
do {
cin>>number;
sum += number;
while(number != 0.0);
return 0;
Output
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: -4
Enter a number: 2
Enter a number: 0
In C++, there are two statements break; and continue; specifically to alter the normal flow of a
program.
Sometimes, it is desirable to skip the execution of a loop for a certain test condition or terminate
it immediately without checking the condition.
For example: You want to loop through data of all aged people except people aged 65. Or, you
want to find the first person aged 20.
The break; statement terminates a loop (for, while and do..while loop) and a switch
statementimmediately when it appears.
Syntax of break
break;
In real practice, break statement is almost always used inside the body of conditional statement
(if...else) inside the loop.
C++ program to add all number entered by user until user enters 0.
#include <iostream>
int main() {
while (true)
if (number != 0.0)
sum += number;
else
break;
return 0;
Output
Enter a number: 4
Enter a number: 0
Sum = 9.6
The user is asked to enter a number which is stored in the variable number. If the user enters any
number other than 0, the number is added to sum and stored to it.
Again, the user is asked to enter another number. When user enters 0, the test expression
inside if statement is false and body of else is executed which terminates the loop.
Syntax of continue
continue;
#include <iostream>
int main()
if ( i == 6 || i == 9)
{
continue;
return 0;
Output
1 2 3 4 5 7 8 10
In above program, when i is 6 or 9, execution of statement cout << i << "\t"; is skipped inside the
loop using continue; statement.
The ladder if..else..if statement allows you to execute a block code among many alternatives. If
you are checking on the value of a single variable in ladder if..else..if, it is better to
use switch statement.
The switch statement is often faster than if...else (not always). Also, the syntax of switch
statement is cleaner and easier to understand.
switch (n)
case constant1:
break;
case constant2:
break;
default:
When a case constant is found that matches the switch expression, control of the program passes
to the block of code associated with that case.
In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute
the block of code associated with the case statement until the end of switch block, or until
the break statement is encountered.
The break statement is used to prevent the code running into the next case.
Flowchart of switch Statement
The above figure shows how a switch statement works and conditions are checked within the
switch case clause.
int main()
char o;
cin >> o;
switch (o)
case '+':
cout << num1 << " + " << num2 << " = " << num1+num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1-num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1*num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1/num2;
break;
default:
break;
return 0;
Output
4.5
The - operator entered by the user is stored in o variable. And, two operands 2.3 and 4.5 are
stored in variables num1 and num2 respectively.
cout << num1 << " - " << num2 << " = " << num1-num2;
If break statement is not used, all cases after the correct case is executed.
C++ goto Statement
In C++ programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...
In the syntax above, label is an identifier. When goto label; is encountered, the control of
program jumps to label: and executes the code below it.
int main()
int i, n;
cin >> n;
goto jump;
sum += num;
jump:
return 0;
Output
Average = 3.95
You can write any C++ program without the use of goto statement and is generally considered a
good idea not to use them.
The goto statement gives power to jump to any part of program but, makes the logic of the
program complex and tangled.
The goto statement can be replaced in most of C++ program with the use of break and continue
statements.
C++ Arrays
In programming, one of the frequently arising problem is to handle numerous data of same type.
Consider this situation, you are taking a survey of 100 people and you have to store their age. To
solve this problem in C++, you can create an integer array having 100 elements.
An array is a collection of data that holds fixed number of values of same type. For example:
int age[100];
Here, the age array can hold maximum of 100 elements of integer type.
The size and type of arrays cannot be changed after its declaration.
dataType arrayName[arraySize];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5
floating-point values.
Suppose you declared an array mark as above. The first element is mark[0], second element
is mark[1] and so on.
Arrays have 0 as the first index not 1. In this example, mark[0] is the first element.
If the size of an array is n, to access the last element, (n-1) index is used. In this
example, mark[4] is the last element.
Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be
2124d, address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
mark[3] = 9;
C++ program to store and calculate the sum of 5 numbers entered by the user using arrays.
#include <iostream>
int main()
sum += numbers[i];
return 0;
Output
Enter 5 numbers: 3
Sum = 18
int testArray[10];
You can use the array members from testArray[0] to testArray[9].
If you try to access array elements outside of its bound, let's say testArray[14], the compiler may
not show any error. However, this may cause unexpected output (undefined behavior).
In C++, you can create an array of an array known as multi-dimensional array. For example:
int x[3][4];
You can think this array as table with 3 rows and each row has 4 columns as shown below.
float x[2][4][3];
This array x can hold a maximum of 24 elements. You can think this example as: Each of the 2
elements can hold 4 elements, which makes 8 elements and each of those 8 elements can hold 3
elements. Hence, total number of elements this array can hold is 24.
Better way to initialise this array with same array elements as above.
int test[2][3][4] = {
};
#include <iostream>
int main()
{
int test[3][2] =
{2, -5},
{4, 0},
{9, 1}
};
cou t<< "test[" << i << "][" << j << "] = " << test[i][j] << endl;
return 0;
Output
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1
C++ Program to store temperature of two different cities for a week and display it.
#include <iostream>
int main()
int temperature[CITY][WEEK];
cout << "Enter all temperature for a week of first city and then second city. \n";
cout << "City " << i + 1 << ", Day " << j + 1 << " : ";
cout << "City " << i + 1 << ", Day " << j + 1 << " = " << temperature[i][j] << endl;
return 0;
Output
Enter all temperature for a week of first city and then second city.
City 1, Day 1 : 32
City 1, Day 2 : 33
City 1, Day 3 : 32
City 1, Day 4 : 34
City 1, Day 5 : 35
City 1, Day 6 : 36
City 1, Day 7 : 38
City 2, Day 1 : 23
City 2, Day 2 : 24
City 2, Day 3 : 26
City 2, Day 4 : 22
City 2, Day 5 : 29
City 2, Day 6 : 27
City 2, Day 7 : 23
Displaying Values:
City 1, Day 1 = 32
City 1, Day 2 = 33
City 1, Day 3 = 32
City 1, Day 4 = 34
City 1, Day 5 = 35
City 1, Day 6 = 36
City 1, Day 7 = 38
City 2, Day 1 = 23
City 2, Day 2 = 24
City 2, Day 3 = 26
City 2, Day 4 = 22
City 2, Day 5 = 29
City 2, Day 6 = 27
City 2, Day 7 = 23
C++ Program to Store value entered by user in three dimensional array and display it.
#include <iostream>
int main()
int test[2][3][2];
cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;
return 0;
Output
Enter 12 values:
1
2
10
11
12
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
As the number of dimension increases, the complexity also increases tremendously although the
concept is quite similar.
Arrays can be passed to a function as an argument. Consider this example to pass one-
dimensional array to a function:
#include <iostream>
int main()
display(marks);
return 0;
Output
Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69
When an array is passed as an argument to a function, only the name of an array is used as
argument.
display(marks);
Also notice the difference while passing array as an argument rather than a variable.
The argument marks in the above code represents the memory address of first element of
array marks[5].
And the formal argument int m[5] in function declaration converts to int* m;. This pointer points
to the same address pointed by the array marks.
That's the reason, although the function is manipulated in the user-defined function with different
array name m[5], the original array marks is manipulated.
C++ handles passing an array to a function in this way to save memory and time.
Multidimensional array can be passed in similar way as one-dimensional array. Consider this
example to pass two dimensional array to a function:
C++ Program to display the elements of two dimensional array by passing it to a function.
#include <iostream>
int main()
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
};
display(num);
return 0;
}
void display(int n[3][2])
Output
Displaying Values:
349571
In the above program, the multi-dimensional array num is passed to the function display().
Inside, display() function, the array n (num) is traversed using a nested for loop.
The program uses 2 for loops to iterate over the elements inside a 2-dimensional array. If it were
a 3-dimensional array, you should use 3 for loops. Finally, all elements are printed onto the
screen.
Note: Multidimensional array with dimension more than 2 can be passed in similar way as two
dimensional array.
References
Turbo C
https://www.programiz.com/c-programming/c-functions
https://www.cprogramming.com/tutorial/lesson1.htm1
Turbo C++
https://www.programiz.com/cpp-programming/function
https://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way