Functions and Character
In this section, you are going to learn
What are the basic properties of a character ?
What is Call by Value ?
What is Call by Reference ?
char c;
Consider a Character
char c;
Let us answer few basic questions about a Character
How many characters can be stored in c
?
See Answer
Number of Characters = 1
How many bytes are there in this Character ?
See Answer
Number of Bytes = 1
What is the sizeof the Character ?
See Answer
sizeof(a) = Number of Bytes = 1
How many bits are there in this Character ?
See Answer
Number of bits = sizeof(c) * 8 = 1 * 8 = 8 bits
Consider a character
char c;
Then below are the properties of a character
Expression |
? |
---|---|
c |
|
&c |
|
*c |
NOT VALID |
sizeof(c) |
1 Byte |
sizeof(&c) |
8 Bytes |
typeof(c) |
|
typeof(&c) |
|
Character passed to a function
Step 1 : Define a character
char c = 5;
Step 2 : Pass character to a function
fun(c);
Step 3 : Define a function
fun
void fun(char c)
{
}
Step 4 : Change character inside function
fun
void fun(char c)
{
c = 10;
}
See full program below
#include <stdio.h>
void fun(char c)
{
c = 10;
}
int main(void)
{
char 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 Character passed to a function
Step 1 : Define a character
char c = 5;
Step 2 : Pass address of character to a function
fun(&c);
Step 3 : Define a function
fun
void fun(char *p)
{
}
Step 4 : Change character inside function
fun
void fun(char *p)
{
*p = 10;
}
See full program below
#include <stdio.h>
void fun(char *p)
{
*p = 10;
}
int main(void)
{
char 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(char c) { } |
Changing |
fun(&c) |
void fun(char *p) { } |
Changing |
Other topics of character and functions
Current Module
Previous Module
Next Module
Other Modules