0% found this document useful (0 votes)
5 views

Working of C ++

Uploaded by

rahimoo2926
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Working of C ++

Uploaded by

rahimoo2926
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Working of C++ "Hello World!

" Program
1. // Your First C++ Program

In C++, any line starting with // is a comment. Comments are intended for the person
reading the code to better understand the functionality of the program. It is completely
ignored by the C++ compiler.
2. #include <iostream>

The #include is a preprocessor directive used to include files in our program. The above
code is including the contents of the iostream file.

This allows us to use cout in our program to print output on the screen.

For now, just remember that we need to use #include <iostream> to use cout that
allows us to print output on the screen.
3. int main() {...}

A valid C++ program must have the main() function. The curly braces indicate the start
and the end of the function.

The execution of code beings from this function.


4. std::cout << "Hello World!";

std::cout prints the content inside the quotation marks. It must be followed by <<
followed by the format string. In our example, "Hello World!" is the format string.

Note: ; is used to indicate the end of a statement.


5. return 0;

The return 0; statement is the "Exit status" of the program. In simple terms, the
program ends with this statement.

Things to take away


 We use std:cout in order to print output on the screen.
 We must include iostream if we want to use std::cout.
 The execution of code begins from the main() function. This function is mandatory. This
is a valid C++ program that does nothing.
int main() {
// Write your code here
}
C++ is a widely used Object Oriented Programming language and is relatively easy to
understand. The “Hello World” program is the first step towards learning any programming
language and is also one of the most straightforward programs you will learn.
The Hello World Program in C++ is the basic program that is used to demonstrate how the
coding process works. All you have to do is display the message “Hello World” on the console
screen.
To write and run C++ programs, you need to set up the local environment on your computer.
Refer to the complete article Setting up C++ Development Environment. If you do not want to
set up the local environment on your computer, you can also use online IDE to write and run
your C++ programs.
C++ Hello World Program
Below is the C++ program to print Hello World.
C++
// C++ program to display
"Hello World"

// Header file for input


output functions

#include <iostream>

using namespace std;

// Main() function: where the


execution of

// program begins

int main()

// Prints hello world

cout << "Hello World";

return 0;

Output
Hello World

Working of Hello World Program in C++


Let us now understand every line and the terminologies of the above program.
1. // C++ program to display “Hello World”
This line is a comment line. A comment is used to display additional information about the
program. A comment does not contain any programming logic.
When a comment is encountered by a compiler, the compiler simply skips that line of code. Any
line beginning with ‘//’ without quotes OR in between /*…*/ in C++ is a comment. Click to
know More about Comments.
2. #include
This is a preprocessor directive. The #include directive tells the compiler to include the content
of a file in the source code.
For example, #include<iostream> tells the compiler to include the standard iostream file which
contains declarations of all the standard input/output library functions. Click to Know More on
Preprocessors.
3. using namespace std
This is used to import the entity of the std namespace into the current namespace of the program.
The statement using namespace std is generally considered a bad practice. When we import a
namespace we are essentially pulling all type definitions into the current scope.
The std namespace is huge. The alternative to this statement is to specify the namespace to which
the identifier belongs using the scope operator(::) each time we declare a type. For example,
std::cout. Click to know More about using namespace std.
4. int main() { }
A function is a group of statements that are designed to perform a specific task. The main()
function is the entry point of every C++ program, no matter where the function is located in the
program.
The opening braces ‘{‘ indicates the beginning of the main function and the closing braces ‘}’
indicates the ending of the main function. Click to know More about the main() function.
5. cout<<“Hello World”;
std::cout is an instance of the std::ostream class, that is used to display output on the screen.
Everything followed by the character << in double quotes ” ” is displayed on the output device.
The semi-colon character at the end of the statement is used to indicate that the statement is
ending there. Click to know More on Input/Output.
6. return 0
This statement is used to return a value from a function and indicates the finishing of a function.
This statement is basically used in functions to return the results of the operations performed by a
function.
7. Indentation
As you can see the cout and the return statement have been indented or moved to the right side.
This is done to make the code more readable. We must always use indentations and comments to
make the code more readable. Must read the FAQ on the style of writing programs.
Important Points
1. Always include the necessary header files for the smooth execution of functions. For example,
<iostream> must be included to use std::cin and std::cout.
2. The execution of code begins from the main() function.
3. It is a good practice to use Indentation and comments in programs for easy understanding.
4. cout is used to print statements and cin is used to take inputs.

C Variables
Variables in C++ is a name given to a memory location. It is the basic unit of storage in a
program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
 In C++, all the variables must be declared before use.

How to Declare Variables?


A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;

// Declaring multiple variables:


type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers, and the
underscore ‘_’ character. However, the name must not start with a number.

Initialization of a variable in C++


In the above diagram,
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:
// Declaring float variable
float simpleInterest;

// Declaring integer variable


int time, speed;

// Declaring character variable


char var;
We can also provide values while declaring the variables as given below:
int a=50,b=100; //declaring 2 variable of integer type
float f=50.8; //declaring 1 variable of float type
char c='Z'; //declaring 1 variable of char type

Rules For Declaring Variable


 The name of the variable contains letters, digits, and underscores.
 The name of the variable is case sensitive (ex Arr and arr both are different variables).
 The name of the variable does not contain any whitespace and special characters (ex #,$,%,*,
etc).
 All the variable names must begin with a letter of the alphabet or an underscore(_).
 We cannot used C++ keyword(ex float,double,class)as a variable name.
Valid variable names:
int x; //can be letters
int _yz; //can be underscores
int z40;//can be letters
Invalid variable names:
int 89; Should not be a number
int a b; //Should not contain any whitespace
int double;// C++ keyword CAN NOT BE USED

Difference Between Variable Declaration and Definition


The variable declaration refers to the part where a variable is first declared or introduced before
its first use. A variable definition is a part where the variable is assigned a memory location and
a value. Most of the time, variable declaration and definition are done together.
See the following C++ program for better clarification:
// C++ program to show difference
between

// definition and declaration of a

// variable

#include <iostream>

using namespace std;

int main()

// this is declaration of
variable a
int a;

// this is initialisation of a

a = 10;

// this is definition =
declaration + initialisation

int b = 20;

// declaration and definition

// of variable 'a123'

char a123 = 'a';

// This is also both declaration


and definition

// as 'c' is allocated memory


and

// assigned some garbage value.

float c;

// multiple declarations and


definitions

int _c, _d45, e;

// Let us print a variable

cout << a123 << endl;

return 0;

Output
a
Time Complexity: O(1)
Space Complexity: O(1)
Types of Variables
There are three types of variables based on the scope of variables in C++
 Local Variables
 Instance Variables
 Static Variables

Types of Variables in C++

Let us now learn about each one of these variables in detail.


1. Local Variables: A variable defined within a block or method or constructor is called a local
variable.
o These variables are created when entered into the block or the function is called and
destroyed after exiting from the block or when the call returns from the function.
o The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access this variable only within that block.
o Initialization of Local Variable is Mandatory.
2. Instance Variables: Instance variables are non-static variables and are declared in a class outside
any method, constructor, or block.
o As instance variables are declared in a class, these variables are created when an object
of the class is created and destroyed when the object is destroyed.
o Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
o Initialization of Instance Variable is not Mandatory.
o Instance Variable can be accessed only by creating objects.
3. Static Variables: Static variables are also known as Class variables.
o These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
o Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
o Static variables are created at the start of program execution and destroyed
automatically when execution ends.
o Initialization of Static Variable is not Mandatory. Its default value is 0
o If we access the static variable like the Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The compiler
will replace the object name with the class name automatically.
o If we access the static variable without the class name, the Compiler will automatically
append the class name.

Instance Variable Vs Static Variable


 Each object will have its own copy of the instance variable whereas We can only have one copy
of a static variable per class irrespective of how many objects we create.
 Changes made in an instance variable using one object will not be reflected in other objects as
each object has its own copy of the instance variable. In the case of static, changes will be
reflected in other objects as static variables are common to all objects of a class.
 We can access instance variables through object references and Static Variables can be
accessed directly using the class name.
 The syntax for static and instance variables:
class Example
{
static int a; // static variable
int b; // instance variable
}

Contants in C

The constants in C are the read-only variables whose values cannot be modified once they are
declared in the C program. The type of constant can be an integer constant, a floating pointer
constant, a string constant, or a character constant. In C language, the const keyword is used to
define the constants.
In this article, we will discuss about the constants in C programming, ways to define constants in
C, types of constants in C, their properties and the difference between literals and constants.
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once it is declared in
the program. We can not make any change in the value of the constant variables after they are
defined.
How to Define Constant in C?
We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.
Syntax to Define Constant
const data_type var_name = value;

Example of Constants in C
// C program to illustrate constant
variable definition

#include <stdio.h>

int main()

// defining integer constant using


const keyword

const int int_const = 25;

// defining character constant


using const keyword
const char char_const = 'A';

// defining float constant using


const keyword

const float float_const = 15.66;

printf("Printing value of Integer


Constant: %d\n",

int_const);

printf("Printing value of Character


Constant: %c\n",

char_const);

printf("Printing value of Float


Constant: %f",

float_const);

return 0;

Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000
One thing to note here is that we have to initialize the constant variables at declaration.
Otherwise, the variable will store some garbage value and we won’t be able to change it. The
following image describes examples of incorrect and correct variable definitions.
Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the list of the
types of constants
 Integer Constant
 Character Constant
 Floating Point Constant
 Double Precision Floating Point Constant
 Array Constant
 Structure Constant
We just have to add the const keyword at the start of the variable declaration.
Properties of Constant in C
The important properties of constant variables in C defined using the const keyword are as
follows:
1. Initialization with Declaration
We can only initialize the constant variable in C at the time of its declaration. Otherwise, it will
store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be initialized only
once in the whole program. After that, we cannot modify the value stored inside that variable.
// C Program to demonstrate the
behaviour of constant

// variable

#include <stdio.h>

int main()

// declaring a constant variable

const int var;

// initializing constant variable


var after declaration

var = 20;

printf("Value of var: %d", var);

return 0;

Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^

Difference Between Constants and Literals


The constant and literals are often confused as the same. But in C language, they are different
entities and have different semantics. The following table lists the differences between the
constants and literals in C:
Constant Literals
Constants are variables that cannot be modified
Literals are the fixed values that define themselves.
once declared.

Constants are defined by using the const keyword They themselves are the values that are assigned to
in C. They store literal values in themselves. the variables or constants.

We cannot determine the address of a literal


We can determine the address of constants.
except string literal.

They are lvalues. They are rvalues.

Example: const int c = 20. Example: 24,15.5, ‘a’, “Geeks”, etc.


Defining Constant using #define Preprocessor
We can also define a constant in C using #define preprocessor. The constants defined using
#define are macros that behave like a constant. These constants are not handled by the compiler,
they are handled by the preprocessor and are replaced by their value before compilation.
#define const_name value
Example of Constant Macro
// C Program to define a constant
using #define

#include <stdio.h>

#define pi 3.14

int main()

printf("The value of pi: %.2f",


pi);

return 0;

Output
The value of pi: 3.14
Note: This method for defining constant is not preferred as it may introduce bugs and make the
code difficult to maintain.
FAQs on C Constants
Q1. Define C Constants.
Answer:
Constants in C are the immutable variables whose values cannot be modified once they are
declared in the C program.
Q2. What is the use of the const keyword?’
Answer:
The const keyword is the qualifier that is used to declare the constant variable in C language.
Q3. Can we initialize the constant variable after the declaration?
Answer:
No, we cannot initialize the constant variable once it is declared.
Q4. What is the right way to declare the constant in C?
Answer:
The right way to declare a constant in C is to always initialize the constant variable when we
declare.
Q5. What is the difference between constant defined using const qualifier
and #define?
Answer:
The following table list the differences between the constants defined using const qualifier and
#define in C:
Constants using const Constants using #define

They are the macros that are replaced by their


They are the variables that are immutable
value.

They are handled by the compiler. They are handled by the preprocessor.

Syntax: const type name = value; Syntax: #define name value

Q6. Is there any way to change the value of a constant variable in C?


Answer:
Yes, we can take advantage of the loophole created by pointers to change the value of a variable
declared as a constant in C. The below C program demonstrates how to do it.
// C Program to change the value of
constant variable

#include <stdio.h>

int main()

// defining an integer constant

const int var = 10;

printf("Initial Value of Constant:


%d\n", var);

// defining a pointer to that const


variable

int* ptr = &var;

// changing value

*ptr = 500;

printf("Final Value of Constant:


%d", var);

return 0;

Output
Initial Value of Constant: 10
Final Value of Constant: 500

Constant Qualifier in C

The qualifier const can be applied to the declaration of any variable to specify that its value will
not be changed (which depends upon where const variables are stored, we may change the value
of the const variable by using a pointer). The result is implementation-defined if an attempt is
made to change a const.
Using the const qualifier in C is a good practice when we want to ensure that some values should
remain constant and should not be accidentally modified.
In C programming, the const qualifier can be used in different contexts to provide various
behaviors. Here are some different use cases of the const qualifier in C:
1. Constant Variables
const int var = 100;
In this case, const is used to declare a variable var as a constant with an initial value of 100. The
value of this variable cannot be modified once it is initialized. See the following example:
// C program to demonstrate that constant
variables can not

// be modified

#include <stdio.h>

int main()

const int var = 100;

// Compilation error: assignment of


read-only variable

// 'var'

var = 200;
return 0;

Output
./Solution.cpp: In function 'int main()':
./Solution.cpp:11:9: error: assignment of read-only variable 'var'
var = 200;
^
2. Pointer to Constant
const int* ptr;
OR
int const *ptr;
We can change the pointer to point to any other integer variable, but cannot change the value of
the object (entity) pointed using pointer ptr. The pointer is stored in the read-write area (stack in
the present case). The object pointed may be in the read-only or read-write area. Let us see the
following examples.
Example 1:
// C program to demonstrate that the
pointer to point to

// any other integer variable, but the


value of the object

// (entity) pointed can not be changed

#include <stdio.h>

int main(void)

int i = 10;

int j = 20;

/* ptr is pointer to constant */

const int* ptr = &i;

printf("ptr: %d\n", *ptr);

/* error: object pointed cannot be


modified

using the pointer ptr */

*ptr = 100;
ptr = &j; /* valid */

printf("ptr: %d\n", *ptr);

return 0;

Output
./Solution.c: In function 'main':
./Solution.c:12:10: error: assignment of read-only location '*ptr'
*ptr = 100;
^
Example 2: Program where variable i itself is constant.
// C program to demonstrate that the
pointer to point to

// any other integer variable, but the


value of the object

// (entity) pointed can not be changed

#include <stdio.h>

int main(void)

/* i is stored in read only area*/

int const i = 10;

int j = 20;

/* pointer to integer constant. Here


i

is of type "const int", and &i is of

type "const int *". And p is of type

"const int", types are matching no


issue */

int const* ptr = &i;


printf("ptr: %d\n", *ptr);

/* error */

*ptr = 100;

/* valid. We call it up
qualification. In

C/C++, the type of "int *" is allowed


to up

qualify to the type "const int *".


The type of

&j is "int *" and is implicitly up


qualified by

the compiler to "const int *" */

ptr = &j;

printf("ptr: %d\n", *ptr);

return 0;

Output
./Solution.c: In function 'main':
./Solution.c:18:10: error: assignment of read-only location '*ptr'
*ptr = 100;
^
Down qualification is not allowed in C++ and may cause warnings in C. Down qualification
refers to the situation where a qualified type is assigned to a non-qualified type.
Example 3: Program to show down qualification.
// C program to demonstrate the down
qualification

#include <stdio.h>

int main(void)

{
int i = 10;

int const j = 20;

/* ptr is pointing an integer object */

int* ptr = &i;

printf("*ptr: %d\n", *ptr);

/* The below assignment is invalid in


C++, results in

error In C, the compiler *may* throw


a warning, but

casting is implicitly allowed */

ptr = &j;

/* In C++, it is called 'down


qualification'. The type

of expression &j is "const int *"


and the type of ptr

is "int *". The assignment "ptr =


&j" causes to

implicitly remove const-ness from


the expression &j.

C++ being more type restrictive,


will not allow

implicit down qualification.


However, C++ allows

implicit up qualification. The


reason being, const

qualified identifiers are bound to


be placed in

read-only memory (but not always).


If C++ allows

above kind of assignment (ptr = &j),


we can use 'ptr'

to modify value of j which is in


read-only memory.

The consequences are implementation


dependent, the

program may fail

at runtime. So strict type checking


helps clean code.

*/

printf("*ptr: %d\n", *ptr);

return 0;

Output
main.c: In function ‘main’:
main.c:16:9: warning: assignment discards ‘const’ qualifier from pointer
target type [-Wdiscarded-qualifiers]
16 | ptr = &j;
| ^
*ptr: 10
*ptr: 20
3. Constant Pointer to Variable
int* const ptr;
The above declaration is a constant pointer to an integer variable, which means we can change
the value of the object pointed by the pointer, but cannot change the pointer to point to another
variable.
Example
// C program to demonstrate that the value
of object pointed

// by pointer can be changed but the pointer


can not point

// to another variable

#include <stdio.h>

int main(void)

int i = 10;
int j = 20;

/* constant pointer to integer */

int* const ptr = &i;

printf("ptr: %d\n", *ptr);

*ptr = 100; /* valid */

printf("ptr: %d\n", *ptr);

ptr = &j; /* error */

return 0;

Output
./Solution.c: In function 'main':
./Solution.c:15:9: error: assignment of read-only variable 'ptr'
ptr = &j; /* error */
^
4. Constant Pointer to Constant
const int* const ptr;
The above declaration is a constant pointer to a constant variable which means we cannot change
the value pointed by the pointer as well as we cannot point the pointer to other variables. Let us
see with an example.
// C program to demonstrate that value
pointed by the

// pointer can not be changed as well as we


cannot point the

// pointer to other variables

#include <stdio.h>

int main(void)

int i = 10;

int j = 20;

/* constant pointer to constant integer


*/

const int* const ptr = &i;

printf("ptr: %d\n", *ptr);

ptr = &j; /* error */

*ptr = 100; /* error */

return 0;

Output
./Solution.c: In function 'main':
./Solution.c:12:9: error: assignment of read-only variable 'ptr'
ptr = &j; /* error */
^
./Solution.c:13:10: error: assignment of read-only location '*ptr'
*ptr = 100; /* error */
^
Advantages of const Qualifiers in C
The const qualifier in C has the following advantages:
 Improved Code Readability: By marking a variable as const, you indicate to other programmers
that its value should not be changed, making your code easier to understand and maintain.
 Enhanced Type Safety: By using const, you can ensure that values are not accidentally modified,
reducing the chance of bugs and errors in your code.
 Improved Optimization: Compilers can optimize const variables more effectively, as they know
that their values will not change during program execution. This can result in faster and more
efficient code.
 Better Memory Usage: By declaring variables as const, you can often avoid having to make a
copy of their values, which can reduce memory usage and improve performance.
 Improved Compatibility: By declaring variables as const, you can make your code more
compatible with other libraries and APIs that use const variables.
 Improved Reliability: By using const, you can make your code more reliable, as you can ensure
that values are not modified unexpectedly, reducing the risk of bugs and errors in your code.
Summary
Pointer Value Change Pointing Value Change
Type Declaration
(*ptr = 100) (ptr = &a)

Pointer to Variable int * ptr Yes Yes

Pointer to Constant const int * ptr No Yes


Pointer Value Change Pointing Value Change
Type Declaration
(*ptr = 100) (ptr = &a)

int const * ptr

Constant Pointer to Variable int * const ptr Yes No

Constant Pointer to Constant const int * const ptr No No

You might also like