The Wayback Machine - https://web.archive.org/web/20240918144503/https://www.geeksforgeeks.org/parameter-passing-techniques-in-c-cpp/
Open In App

Parameter Passing Techniques in C

Last Updated : 16 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C, there are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case, A is called the “caller function” and B is called the “called function or callee function”. Also, the arguments which A sends to B are called actual arguments and the parameters of B are called formal arguments.

Terminology

  • Formal Parameter: A variable and its type as it appears in the prototype of the function or method.
  • Actual Parameter: The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment.
  • Modes:
    • IN: Passes info from caller to the callee.
    • OUT: Callee writes values in the caller.
    • IN/OUT: The caller tells the callee the value of the variable, which the callee may update.

Methods of Parameter Passing in C

There are two ways in which we can pass the parameters to the function in C:

1. Pass By Value

This method uses in-mode semantics. Changes made to formal parameters do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called call by value.

 

Example of Pass by Value

The below example demonstrates pass by value in function.

C




// C program to illustrate
// call by value
#include <stdio.h>
  
void func(int a, int b)
{
    a += b;
    printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
    int x = 5, y = 7;
  
    // Passing parameters
    func(x, y);
    printf("In main, x = %d y = %d\n", x, y);
    return 0;
}


Output

In func, a = 12 b = 7
In main, x = 5 y = 7

Shortcomings of Pass By Value:

  • Inefficiency in storage allocation
  • For objects and arrays, the copy semantics are costly

Note: Languages like C, C++, and Java support this type of parameter passing. Java in fact is strictly call by value.

C doesn’t support call by reference.

2. Pass by Pointers

This technique uses a pointer. In function we pass memory address (pointer) of a variable rather than passing the actual value of variable. This passing technique allows the function to access and modify the content at that particular memory location.

Example of Pass by Pointers

C




// C program to demonstrate the pass by pointer in Function
  
#include <stdio.h>
  
// Function to modify the value passed as pointer to an int
void modifyVal(int* myptr)
{
    // Access and modifying the value pointed by myptr
    *myptr = *myptr + 5;
}
  
int main()
{
  
    int x = 5;
    int* myptr = &x;
  
    // Passing the pointer ptr to the function
    modifyVal(myptr);
  
    // printitng the modified value of x
    printf("Modified value of x is: %d\n", x);
    return 0;
}


Output

Modified value of x is: 10

Shortcomings of Pass by Pointers

  • Pointers can be null so null pointer Issues arises if properly not checked.
  • If more than one pointers point to the same memory location then changes made by one pointer affect other the other pointers which points to same memory location.
  • memory management should be done effectively using function like malloc and free.

Other Methods of Parameter Passing

These techniques are older and were used in earlier programming languages like Pascal, Algol, and Fortran. These techniques are not applicable in high-level languages.

1. Pass by Result

This method uses out-mode semantics. Just before control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called call by the result. In general, the pass-by-result technique is implemented by copying.

2. Pass by Value-Result

This method uses in/out-mode semantics. It is a combination of Pass-by-Value and Pass-by-Result. Just before the control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called call by value-result.

3. Pass by Name

This technique is used in programming languages such as Algol. In this technique, the symbolic “name” of a variable is passed, which allows it both to be accessed and updated.

Example

To double the value of C[j], you can pass its name (not its value) into the following procedure.

procedure double(x);
  real x;
begin 
  x:=x*2
end;

In general, the effect of pass-by-name is to textually substitute the argument in a procedure call for the corresponding parameter in the body of the procedure. Implications of Pass-by-Name mechanism:

  • The argument expression is re-evaluated each time the formal parameter is passed.
  • The procedure can change the values of variables used in the argument expression and hence change the expression’s value.

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



Previous Article
Next Article

Similar Reads

Parameter Passing Techniques in C++
In C++, data must be sent to functions when they are called in order to perform operations. This data is called parameters or arguments and there are various parameter passing methods available in C++, each with merits and demerits of its own. In this article, we will discuss various parameter-passing techniques in C++. Basic TerminologiesFunction
4 min read
Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing by Pointer Here, the memory location (address) of
5 min read
Passing a vector to constructor in C++
When class member is a vector object (not a reference).We can simply assign in constructor. C/C++ Code // Passing vector object to a constructor. #include &amp;lt;iostream&amp;gt; #include &amp;lt;vector&amp;gt; using namespace std; class MyClass { vector&amp;lt;int&amp;gt; vec; public: MyClass(vector&amp;lt;int&amp;gt; v) { vec = v; } void print()
2 min read
How to delete an element from the Set by passing its value in C++
Given a Set, the task is to remove the last element from this Set in C++.Examples: Input: set = [10 20 30 70 80 90 100 40 50 60], valueOfElementToBeDeleted = 100 Output: 10 20 30 40 50 60 70 80 90 Input: set = [1 2 3 4 5], valueOfElementToBeDeleted = 3 Output: 1 2 4 5 Sets are a type of associative container in which each element has to be unique b
6 min read
Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Passing Pointers to Functions in C
Prerequisites: Pointers in CFunctions in C Passing the pointers to the function means the memory location of the variables is passed to the parameters in the function, and then the operations are performed. The function definition accepts these addresses using pointers, addresses are stored using pointers. Arguments Passing without pointer When we
2 min read
Passing Map as Reference in C++ STL
Prerequisite: Maps in C++ STL Pass by reference Elements in the map are in form of pairs where the first is key and another value, denoting key-value pairs. Also, all the key values are unique means no two elements can have the same key value. Passing maps by value is a costly task, costly in terms of computation and memory resources. When we pass
3 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
Passing NULL to printf in C
Consider the following C code snippet. char* p = NULL; printf("%s", p); What should be the output of the above program? The print expects a '\0' terminated array of characters (or string literal) whereas it receives a null pointer. Passing NULL to printf is undefined behavior. According to Section 7.1.4(of C99 or C11) : Use of library functions If
1 min read
Passing Vector to a Function in C++
When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By valuePass By Reference When a vector is passed to a function, a copy of the vector is created. This new copy of the vector is then used in the function and thus, any changes made to the vector in the function do not affe
3 min read
Difference between Argument and Parameter in C/C++ with Examples
Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in
4 min read
How to pass a 2D array as a parameter in C?
This post is an extension of How to dynamically allocate a 2D array in C? A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a function can be difficult to remember. One important thing for passing multidimensional arrays is, first array dimension does not have to be specified. The second (and any subseq
3 min read
How to print size of array parameter in C++?
How to compute the size of an array CPP? C/C++ Code // A C++ program to show that it is wrong to  // compute size of an array parameter in a function #include &lt;iostream&gt; using namespace std; void findSize(int arr[]) { cout &lt;&lt; sizeof(arr) &lt;&lt; endl; } int main() { int a[10]; cout &lt;&lt; sizeof(a) &lt;&lt; &quot; &quot;; findSize(a)
3 min read
Optimization Techniques | Set 2 (swapping)
How to swap two variables? The question may look silly, neither geeky. See the following piece of code to swap two integers (XOR swapping), void myswap(int *x, int *y) { if (x != y) { *x^=*y^=*x^=*y; } } At first glance, we may think nothing wrong with the code. However, when prompted for reason behind opting for XOR swap logic, the person was clue
1 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Article Tags :
Practice Tags :