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 ?

How many bytes are there in this Character ?

What is the sizeof the Character ?

How many bits are there in this Character ?

Consider a character

char c;

Then below are the properties of a character

Expression

?

c

c is a character

&c

&c is address of character c

*c

NOT VALID

sizeof(c)

1 Byte

sizeof(&c)

8 Bytes

typeof(c)

char

typeof(&c)

char *

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 of main

  • variable c is created on stack frame of fun

  • Even though name of variable c is same in main and fun, they are two different variables in memory

  • Hence changing value of c inside function fun does not change the value of c inside main

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 parameter

  • LHS 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 changes c. Because we proved *p is equal to c

Function Call

Function Definition

Observations

fun(c)

void fun(char c) { }

Changing c inside fun DOES NOT change value of c in caller

fun(&c)

void fun(char *p) { }

Changing *p inside fun CHANGES value of c in caller