Functions in C-1 | Programming and Data Structures - Computer Science Engineering (CSE) PDF Download

Functions in C/C++

A function is a set of statements that take inputs, do some specific computation and produces output.
The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can call the function.
The general form of a function is:
return_type function_name([ arg1_type arg1_name, ... ]) { code }

Example:
Below is a simple C/C++ program to demonstrate functions:
C
#include <stdio.h>
// An example function that takes two parameters 'x' and 'y'
// as input and returns max of two input numbers
int max(int x, int y)
{
    if (x > y)
      return x;
    else
      return y;
}
// main function that doesn't receive any parameter and
// returns integer.
int main(void)
{
    int a = 10, b = 20;
    // Calling above function to find max of 'a' and 'b'
    int m = max(a, b);
    printf("m is %d", m);
    return 0;
}

C++
#include <iostream>
using namespace std;
int max(int x, int y)
{
    if (x > y)
    return x;
    else
    return y;
}
int main() {
    int a = 10, b = 20;
    // Calling above function to find max of 'a' and 'b'
    int m = max(a, b);
    cout << "m is " << m;
    return 0;
}
Output:
m is 20

Why do we need functions?
  • Functions help us in reducing code redundancy. If functionality is performed at multiple places in software, then rather than writing the same code, again and again, we create a function and call it everywhere. This also helps in maintenance as we have to change at one place if we make future changes to the functionality.
  • Functions make code modular. Consider a big file having many lines of codes. It becomes really simple to read and use the code if the code is divided into functions.
  • Functions provide abstraction. For example, we can use library functions without worrying about their internal working.

Function Declaration

A function declaration tells the compiler about the number of parameters function takes, data-types of parameters and return type of function. Putting parameter names in function declaration is optional in the function declaration, but it is necessary to put them in the definition. Below are an example of function declarations. (parameter names are not there in below declarations)
Functions in C-1 | Programming and Data Structures - Computer Science Engineering (CSE)// A function that takes two integers as parameters
// and returns an integer
int max(int, int);

// A function that takes a int pointer and an int variable as parameters
// and returns an pointer of type int
int *swap(int*,int);

// A function that takes a charas parameters
// and returns an reference variable
char *call(char b);

// A function that takes a char and an int as parameters
// and returns an integer
int fun(char, int);

It is always recommended to declare a function before it is used (See this, this and this for details)
In C, we can do both declaration and definition at the same place, like done in the above example program.
C also allows to declare and define functions separately, this is especially needed in case of library functions. The library functions are declared in header files and defined in library files. Below is an example declaration.

Parameter Passing to functions

The parameters passed to function are called actual parameters. For example, in the above program 10 and 20 are actual parameters.
The parameters received by function are called formal parameters. For example, in the above program x and y are formal parameters.

There are two most popular ways to pass parameters:
1. Pass by Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of caller.
2. Pass by Reference Both actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in actual parameters of caller.
Parameters are always passed by value in C. For example. in the below code, value of x is not modified using the function fun().

C
#include <stdio.h>
void fun(int x)
{
   x = 30;
}
int main(void)
{
    int x = 20;
    fun(x);
    printf("x = %d", x);
    return 0;
}

C++
#include <iostream>
using namespace std;
void fun(int x) {
    x = 30;
}
int main() {
    int x = 20;
    fun(x);
    cout << "x = " << x;
    return 0;
}
Output:
x = 20

However, in C, we can use pointers to get the effect of pass by reference. For example, consider the below program. The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value at the address ptr. The dereference operator * is used to access the value at an address. In the statement ‘*ptr = 30’, value at address ptr is changed to 30. The address operator & is used to get the address of a variable of any data type. In the function call statement ‘fun(&x)’, the address of x is passed so that x can be modified using its address.

C
# include <stdio.h>
void fun(int *ptr)
{
    *ptr = 30;
}
int main()
{  int x = 20;
  fun(&x);
  printf("x = %d", x);
  return 0;
}

C++
#include <iostream>
using namespace std;
void fun(int *ptr)
{
    *ptr = 30;
}
int main() {
    int x = 20;
    fun(&x);
    cout << "x = " << x;
    return 0;
}
Output:
x = 30

Following are some important points about functions in C:

  1. Every C program has a function called main() that is called by operating system when a user runs the program.
  2. Every function has a return type. If a function doesn’t return any value, then void is used as return type. Moreover, if the return type of the function is void, we still can use return statement in the body of function definition by not specifying any constant, variable, etc. with it, by only mentioning the ‘return;’ statement which would symbolise the termination of the function as shown below:
    void function name(int a)
    {
    .......  //Function Body
    return;  //Function execution would get terminated
    }
  3. In C, functions can return any type except arrays and functions. We can get around this limitation by returning pointer to array or pointer to function.
  4. Empty parameter list in C mean that the parameter list is not specified and function can be called with any parameters. In C, it is not a good idea to declare a function like fun(). To declare a function that can only be called without any parameter, we should use “void fun(void)”.
    As a side note, in C++, empty list means function can only be called without any parameter. In C++, both void fun() and void fun(void) are same.
  5. If in a C program, a function is called before its declaration then the C compiler automatically assumes the declaration of that function in the following way:
    int function name();
    And in that case if the return type of that function is different than INT ,compiler would show an error.

Main Function

The main function is a special function. Every C++ program must contain a function named main. It serves as the entry point for the program. The computer will start running the code from the beginning of the main function.

Types of main Function

  1. The first type is – main function without parameters:
    // Without Parameters
    int main()
    {
       ...
       return 0;
    }
  2. Second type is main function with parameters:
    // With Parameters
    int main(int argc, char * const argv[])
    {
       ...
       return 0;
    }

The reason for having the parameter option for the main function is to allow input from the command line.
When you use the main function with parameters, it saves every group of characters (separated by a space) after the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a return statement in the code. The number that is returned is used to inform the calling program what the result of the program’s execution was. Returning 0 signals that there were no problems.

How to Count Variable Numbers of Arguments in C?

C supports variable numbers of arguments. But there is no language provided way for finding out total number of arguments passed. User has to handle this in one of the following ways:

  1. By passing first argument as count of arguments.
  2. By passing last argument as NULL (or 0).
  3. Using some printf (or scanf) like mechanism where first argument has placeholders for rest of the arguments.

Following is an example that uses first argument arg_count to hold count of other arguments:
#include <stdarg.h>
#include <stdio.h>
// this function returns minimum of integer numbers passed.  First
// argument is count of numbers.
int min(int arg_count, ...)
{
  int i;
  int min, a;
  // va_list is a type to hold information about variable arguments
  va_list ap;
  // va_start must be called before accessing variable argument list
  va_start(ap, arg_count);
  // Now arguments can be accessed one by one using va_arg macro
  // Initialize min as first argument in list  
  min = va_arg(ap, int);
  // traverse rest of the arguments to find out minimum
  for(i = 2; i <= arg_count; i++) {
    if((a = va_arg(ap, int)) < min)
      min = a;
  }  
  //va_end should be executed before the function returns whenever
  // va_start has been previously used in that function
  va_end(ap);
  return min;
}
int main()
{
   int count = 5;
   // Find minimum of 5 numbers: (12, 67, 6, 7, 100)
   printf("Minimum value is %d", min(count, 12, 67, 6, 7, 100));
   getchar();
   return 0;
}
Output:
Minimum value is 6

What is evaluation order of function parameters in C?

It is compiler dependent in C. It is never safe to depend on the order of evaluation of side effects. For example, a function call like below may very well behave differently from one compiler to another:
void func (int, int);
int i = 2;
func (i++, i++);
There is no guarantee (in either the C or the C++ standard language definitions) that the increments will be evaluated in any particular order. Either increment might happen first. func might get the arguments `2, 3′, or it might get `3, 2′, or even `2, 2′.

The document Functions in C-1 | Programming and Data Structures - Computer Science Engineering (CSE) is a part of the Computer Science Engineering (CSE) Course Programming and Data Structures.
All you need of Computer Science Engineering (CSE) at this link: Computer Science Engineering (CSE)
119 docs|30 tests

Top Courses for Computer Science Engineering (CSE)

FAQs on Functions in C-1 - Programming and Data Structures - Computer Science Engineering (CSE)

1. What is a function in C/C++?
Ans. A function in C/C++ is a self-contained block of code that performs a specific task. It can take input parameters, perform computations, and return a value (if required). Functions help in organizing the code and make it modular and reusable.
2. How do you define a function in C/C++?
Ans. To define a function in C/C++, you need to provide the function signature (return type, function name, and parameter list) followed by the function body enclosed in curly braces. Here's an example: ```c int addNumbers(int a, int b) { int sum = a + b; return sum; } ``` This function, named "addNumbers," takes two integer parameters (a and b), calculates their sum, and returns the result.
3. What is the purpose of a return statement in a function?
Ans. The return statement is used to exit a function and return a value back to the caller. It allows the function to provide the result of its computation or any other information back to the calling code. Without a return statement, the function may not provide any value or result to the caller.
4. How are function parameters passed in C/C++?
Ans. Function parameters in C/C++ can be passed by value or by reference. - When passed by value, a copy of the parameter's value is made, and any modifications made within the function do not affect the original value. - When passed by reference, the parameter is a reference to the original value, and any modifications made within the function will affect the original value. In C++, you can also use references or pointers as function parameters to achieve pass-by-reference behavior explicitly.
5. Can a function in C/C++ have multiple return statements?
Ans. Yes, a function in C/C++ can have multiple return statements. However, it is generally considered good practice to have a single exit point in a function for better code readability and maintainability. Multiple return statements can make the code more complex and harder to understand.
119 docs|30 tests
Download as PDF
Explore Courses for Computer Science Engineering (CSE) exam

Top Courses for Computer Science Engineering (CSE)

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Important questions

,

practice quizzes

,

Functions in C-1 | Programming and Data Structures - Computer Science Engineering (CSE)

,

Functions in C-1 | Programming and Data Structures - Computer Science Engineering (CSE)

,

Extra Questions

,

past year papers

,

Viva Questions

,

ppt

,

Free

,

MCQs

,

mock tests for examination

,

Exam

,

video lectures

,

Semester Notes

,

Sample Paper

,

Previous Year Questions with Solutions

,

pdf

,

Summary

,

Objective type Questions

,

Functions in C-1 | Programming and Data Structures - Computer Science Engineering (CSE)

,

shortcuts and tricks

,

study material

;