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
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 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
&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(char c) { } |
Changing |
fun(&c) |
void fun(char *p) { } |
Changing |
Other topics of character and functions
Current Module
Previous Module
Next Module
Other Modules