Block and Scope - Tinh
Block and Scope - Tinh
Wrong
What happened?
Explanation
• What happens if you declare a variable in a block that has
the same name as the one outside the block?
• Answer
The new variable hides the old one from its point of
appearance until the end of the block.
Then the old one becomes visible again when the
program runs to the end of the block.
The purpose of using functions
• The purpose of using functions is
to break a large task into smaller
ones.
• This allows a developer to build on
what has already been finished
instead of starting over from
scratch (do it again many times
from the initial point).
Create your own functions
• when you create your own functions, you have to handle all three
aspects:
• Provide a function definition.
• Provide a function prototype
• Call the function.
What is prototype? (Nguyên mẫu là gì?)
prototype is the first design of something from which other forms are
copied or developed.
What is prototype?
A prototype describes the functional interface to the compiler. That is, it tells
the compiler: what type of return value, if any, and the number and type of
function arguments.
arguments
The purpose of using functions
Header of functions
Function simple() has its function header:
void simple()
The initial void means that simple() has no return value. Thus, calling simple()
doesn’t produce a number that you can assign to a variable in main().
int main()
{
simple(); // ok for void functions
int a;
a = simple(); // Wrong. Not allowed for void functions
}
Definition of a function
Functions into two categories: those that don’t have return values and
those that do.
Functions without return values are termed type void functions and have
the following general form:
void functionName(parameterList)
{
statement(s);
}
Here parameterList specifies the types and number of arguments
(parameters) passed to the function.
Definition of a function
Definition of a function
A function with a return value produces a value. Such a function is declared as having
the same type as the value it returns.
typeName functionName(parameterList)
{
statements;
return value; // value is type cast to type typeName
}