General Discussions

Understanding Various Call by Mechanisms – Structures and Functions

The medium picked to understand the said is by the following:

  • Passing the structure members to the function by call by value or call by reference
  • Passing structures to functions using pass by value
  • Passing structures to functions using pass by reference

1. Demonstrating call by value and reference when a function is passed with members of a structure:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student
{
	char name[20];
	int effort;
	float marks;
};

void update_marks(int effort, float *marks)
{
	if(effort == 1)
	{
		if(*marks <=40)
			*marks = *marks + *marks * 0.25;
	}
}

int main()
{
	struct student s1;
	strcpy(s1.name, "new");
	s1.marks = 30;
	s1.effort = 1;
	// Notice that one member is passed as call by value (effort is only to check status) and another by reference as marks need to be updated)
	update_marks(s1.effort, &s1.marks);
	printf("Student Details:\n");
	printf("Name: %s\nMarks: %f\n", s1.name, s1.marks);
	return 0;
}

2. Passing structures to functions using pass by value

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student
{
	char name[20];
	int effort;
	float marks;
};

struct student update_marks(struct student s1)
{
	if(s1.effort == 1)
	{
		if(s1.marks <=40)
			s1.marks = s1.marks + s1.marks * 0.25;
	}
	return s1;
}

int main()
{
	struct student s1;
	strcpy(s1.name, "new");
	s1.marks = 30;
	s1.effort = 1;
	// Structure is passed by call by value. Hence the return type to hold the returned updated result
	s1 = update_marks(s1);
	printf("Student Details:\n");
	printf("Name: %s\nMarks: %f\n", s1.name, s1.marks);
	return 0;
}

3. Passing structures to functions using pass by reference

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student
{
	char name[20];
	int effort;
	float marks;
};

void update_marks(struct student *s1)
{
	if(s1->effort == 1)
	{
		if(s1->marks <=40)
                   s1->marks = s1->marks + s1->marks * 0.25;
	}
}

int main()
{
	struct student s1;
	strcpy(s1.name, "new");
	s1.marks = 30;
	s1.effort = 1;
	// Pass the address of the structure. Notice the change is function call and function definition.
	update_marks(&s1);
	printf("Student Details:\n");
	printf("Name: %s\nMarks: %f\n", s1.name, s1.marks);
	return 0;
}

 

Advertisements

2 thoughts on “Understanding Various Call by Mechanisms – Structures and Functions

Let me Know What you Think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s