Functions and Integer
In this section, you are going to learn
What are the basic properties of a integer ?
What is Call by Value ?
What is Call by Reference ?
Topics in this section,
int c;
Consider a Integer
int c;
Let us answer few basic questions about a Integer
How many integers can be stored in c
?
See Answer
Number of Integers = 1
How many bytes are there in this Integer ?
See Answer
Number of Bytes = 4
What is the sizeof the Integer ?
See Answer
sizeof(a) = Number of Bytes = 4
How many bits are there in this Integer ?
See Answer
Number of bits = sizeof(c) * 8 = 4 * 8 = 32 bits
Consider a integer
int c;
Then below are the properties of a integer
Expression |
? |
---|---|
c |
|
&c |
|
*c |
NOT VALID |
sizeof(c) |
4 Bytes |
sizeof(&c) |
8 Bytes |
typeof(c) |
|
typeof(&c) |
|
Integer passed to a function
Step 1 : Define a integer
int c = 5;
Step 2 : Pass integer to a function
fun(c);
Step 3 : Define a function
fun
void fun(int c)
{
}
Step 4 : Change integer inside function
fun
void fun(int c)
{
c = 10;
}
See full program below
#include <stdio.h>
void fun(int c)
{
c = 10;
}
int main(void)
{
int c = 5;
printf("Before : c = %d\n", c);
fun(c);
printf("After : c = %d\n", c);
return 0;
}
See full program below
Before : c = 5
After : c = 5
Can you guess what is happening ?
After function fun
is called,
There are two stack frames
Stack frame of
main
Stack frame of
fun
variable
c
is created on stack frame ofmain
variable
c
is created on stack frame offun
Even though name of variable
c
is same inmain
andfun
, they are two different variables in memoryHence changing value of
c
inside functionfun
does not change the value ofc
insidemain
Address of Integer passed to a function
Step 1 : Define a integer
int c = 5;
Step 2 : Pass address of integer to a function
fun(&c);
Step 3 : Define a function
fun
void fun(int *p)
{
}
Step 4 : Change integer inside function
fun
void fun(int *p)
{
*p = 10;
}
See full program below
#include <stdio.h>
void fun(int *p)
{
*p = 10;
}
int main(void)
{
int c = 5;
printf("Before : c = %d\n", c);
fun(&c);
printf("After : c = %d\n", c);
return 0;
}
Output is as below
Before : c = 5
After : c = 10
Can you guess what is happening ?
Let us solve it with equations method !
Rule 1 : Base Rule
p = &c
RHS is actual parameter. In this case
&c
is actual parameterLHS is formal parameter. In this case
p
is formal parameter
Rule 2 : Move
&
from RHS to LHS. This becomes*
on LHS
*p = c
Rule 3 : Changing
*p
also changesc
. Because we proved*p
is equal toc
Function Call |
Function Definition |
Observations |
---|---|---|
fun(c) |
void fun(int c) { } |
Changing |
fun(&c) |
void fun(int *p) { } |
Changing |
Other topics of integer and functions
Current Module
Previous Module
Next Module
Other Modules