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
mainStack frame of
funvariable
cis created on stack frame ofmainvariable
cis created on stack frame offunEven though name of variable
cis same inmainandfun, they are two different variables in memoryHence changing value of
cinside functionfundoes not change the value ofcinsidemain
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
&cis actual parameterLHS is formal parameter. In this case
pis formal parameter
Rule 2 : Move
&from RHS to LHS. This becomes*on LHS
*p = c
Rule 3 : Changing
*palso changesc. Because we proved*pis 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