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

07 - C Basics - Functions

The document provides an overview of functions in C programming, explaining their importance for organization, simplification, and reusability of code. It covers key concepts such as function definitions, declarations, prototypes, calls, return statements, and variable scope. Additionally, it discusses function overloading and the distinction between parameters and arguments.

Uploaded by

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

07 - C Basics - Functions

The document provides an overview of functions in C programming, explaining their importance for organization, simplification, and reusability of code. It covers key concepts such as function definitions, declarations, prototypes, calls, return statements, and variable scope. Additionally, it discusses function overloading and the distinction between parameters and arguments.

Uploaded by

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

C Basics

07 - Functions
/AhmedHatemS

/c/AhmedHatemS
What is the content?
1. Why Functions?

2. A Function Definition.

3. Function declaration.

4. Function prototype.

5. Function Calls.

6. Function Prototype.

7. The Return Statement.

8. Returning Void.

9. Parameters versus Arguments.

10. Function overloading.

11. Variables’ scope.


Why #include <stdio.h>
i n t main() {
Functions? i n t threePowerFour = 1 ;
f o r ( i n t i = 0 ; i < 4 ; i = i + 1)
{
threePowerFour = threePowerFour * 3;
Copy-Paste }
Printf(" 3^4 i s % d " , threePowerFour);
Coding i n t sixPowerFive = 1 ;
f o r ( i n t i = 0 ; i < 5 ; i = i + 1)
(bad!) {
sixPowerFive = sixPowerFive * 6;
}
Printf( " 6^5 i s %d" , sixPowerFive);
i n t twelvePowerTen = 1 ;
f o r ( i n t i = 0 ; i < 10; i = i + 1)
{
twelvePowerTen = twelvePowerTen * 12;
}
Printf( " 12^10 i s % d ", twelvePowerTen);
return 0;
}
Why
Functions?

Instead ..
#include <stdio.h>
with a
/ * Some code which raises an a r b i t r a r y
function in t e g e r t o an a r b i t r a r y power */

i n t main()
{
i n t threePowerFour = raiseToPower( 3, 4 ) ;
Printf(" 3^4 i s % d " , threePowerFour);
i n t sixPowerFive = raiseToPower( 6, 5 ) ;
Printf( " 6^5 i s %d" , sixPowerFive);
i n t twelvePowerTen = raiseToPower( 12, 1 0 ) ;
Printf( " 12^10 i s % d ", twelvePowerTen);
return 0;
}
Functions .. An Overview
• Functions are reusable sections of code that serve a
particular purpose.
• Functions can take inputs and outputs, and can be reused
across programs.
• Organizing programs into functions helps to organize and
simplify code.
• This is an example of abstraction; after you've written a
function, you can use the function without having to worry
about the details of how the function is implemented.
Because of abstraction, others can use (or "call") the
function without knowing its lower-level details as well.
• All programs you've written in C already have one function: main. However,
programs in C can have more functions as well.
• Think of a function as a black box with a set of inputs and a single (optional)
output.

• The rest of the program does not need to know what goes on inside the
function, but the program can call the function, provide it with inputs, and
use the output.
• You've probably used plenty of functions already like cout<< from the
iostream library or pow() from the math library.
• But now we'll learn how to write our own functions and incorporate them
into our code. Basically the point of functions in C is to help you to partition
your code into manageable pieces.
Why Functions?

The main reasons for using functions in programming are:


• Organization; Functions help to break up a complicated problem into more
manageable subparts and help to make sure concepts flow logically into one another.

• Simplification; Smaller components are easier to design, easier to implement, and far
easier to debug. Good use of functions makes code easier to read and problems
easier to isolate.

• Reusability; Functions only need to be written once, and then can be used as many
times as necessary, so you can avoid duplication of code.
A Function Definition
A function definition has a header and a body.
The header always contains these parts:
• Return type; The type of value that the function will output. In our
example, it is int.
• Function name; The name that is used to call this function. In our
example, it is cube.
• Parameter list; The parameters are the types of arguments the
function expects as input, and the names by which the function will
refer to those inputs. cube() takes an int as its only argument, and this
int will be referred to as input in the function's body. Note that the
parameter's list can be empty (indicating that the function doesn't
expect any arguments).
The body is the code within the curly braces that is executed when the
function is called.
• It's important to remember that variables declared in the body of a function
are local in scope to that function and cannot be used in other functions!
• One or more of the statements in the function's body can be return
statements. A return statement ends the execution of the function and passes
the return value back to the function that called it.

Write a program to get the cube of an


entered number using functions.
Function Declaration Syntax
Function Declaration
• Function declarations need to occur before
invocations.
• Solution 1: reorder function declarations.

For example:
i n t bar()
{
return 3;
}

i n t foo()
{
r e t u r n b a r ( ) * 2 ; / / Ok
}
• Function declarations need to occur before
invocations.
• Solution 1: reorder function declarations.
• Solution 2: use a function prototype; it informs
t h e c o m p i l e r t h a t y o u w i l l i m p l e m e n t i t l a t e r.

For example:
i n t bar(); Function Prototype
i n t foo()
{
r e t u r n b a r ( ) * 2 ; / / Ok
}

i n t bar()
{
return 3;
}
Function Prototype
• Function prototypes should match the
signature of the method, though argument
n a m e s d o n ’ t m a t t e r.

For example:

i n t square( int ); i n t sq u are( i n t x ) ; i n t sq u are( i n t z ) ;

i n t cube( int x ) i n t cube( int x ) i n t cube( int x )


{ { {
r e t u r n x*square(x); r e t u r n x*square(x); r e t u r n x*square(x);
} } }

i n t square( int x ) i n t square( int x ) i n t square( int x )


{ { {
return x*x; return x*x; return x*x;
} } }
Function Calls
A program to find the square and the cube of a number in two ways.
More built-in functions
• abs(num);
• toupper(letter);
• tolower(letter);
• sqrt(num);
• floor(num);
• ceil(num);
Returning a Value
▪ Up to one value may be returned; it must be the same type as the return type.
▪ If no values are returned, give the function a void return type.
▪ Note that you cannot declare a variable of type void.
▪ Return statements don’t necessarily need to be at the end.
▪ Function returns as soon as a return statement is executed.
Example 1:
Example 2:

int f o o ( )
vo id printNumber( int num )
{
{
return " h e l l o " ; / / e r r o r
Printf("number is %d", num);
}
}
Example 3:
On the other hand:
int main()
i n t main()
{
int f o o ( ) {
printNumber( 4 ); // the number is 4
{ voi d x ; / / ERROR
return 0;
return 2 ; / / o k return 0;
}
} }
Argument Type Matters? Note that:
Argument is the variable sent
v o i d printOnNewLine( i n t x ) on function call.
{ Parameter is the variable
declared in function’s header
c o u t << x < < e n dl ;
to receive the argument.
}
3 and “hello” are arguments,
Consider the following function invocations? but x is parameter.
• printOnNewLine( 3 )
• printOnNewLine("hello")

Will anyone of them result in an error?

• printOnNewLine( 3 ) works
• printOnNewLine("hello") will not compile
Function Overloading
• Many functions with the same name, but different arguments.
• The function called is the one whose arguments match the invocation.
For example:
void printOnNewLine( int x )
{
cout<<x;
}
void printOnNewLine( char x )
{
cout<<x;
}
void printOnNewLine( int x, int y )
{
cout<<x<<“ ”<<y;
}
• printOnNewLine( 3 ) prints “Integer: 3”
• printOnNewLine('A' ) prints “Character: A”
• printOnNewLine( 4, 5 ) prints “Tw o Integers: 4,5”
Variables’ scope

• A global variable is valid from the point it is declared to the end of


the program.
• A local variable’s scope is limited to the block where it is declared and
cannot be accessed (set or read) outside that block.
• A block is a section of code enclosed in curly braces ({ }).
Next

You might also like