0
how to define a functions in c++ and how to use scope resolution in program and what its use???
3 ответов
+ 1
to define a function in c++, use the following syntax-
return-type name(optional arguments)
{
some code
}
example-
int sum(int a, int b)
{
int num=a+b;
return num;
}
and as for scope resolution operator, it is basically used when you have two variables of the same name out of which one is local and one is global. So, if you want to use the local variable, you just refer it by its name and if you want to use the global variable, you use scope resolution operator(::) before its name.
An upvote will be highly appreciated😊
+ 1
You may define a function by:
type function_name(type arg 1,....,type arg n)
{
Declare a local variable;
executable statements 1 i.e cout;
executable statements 2 i.e cout;
.
.
.
return(expression);
}
It is a little complicated to understand. Try with some examples and you will get it.
Scope resolution (::) is used when you have two same variable of same data type in a program. If the first variable is global and the second is used in a local function then the scope differentiates the two variables. Just understand this code:
#include<iostream>
int a=20;
void main()
{
int a=10;
cout<<"local variable a="<<a;
cout<<"global variable a="<<::a;
}
Here actually 'a=10' in the void main() function is local to its own main body and can be used within itself. But the 'a=20' is global and can be used in the whole program. But compiler is confused between two values of 'a'. Hence to print or work on a global variable in the local body of a program, the scope resolution is uses i.e in the above the global variable is uses to print by using global a=20 as ::a .
If you have any doubt, you are welcomed to ask.
0
thanks for answering me