C documentation V1 Help

Arguments and Parameters

In C programming, functions often utilize parameters to receive input values, and arguments are the actual values passed to the function when it is called. Let's explore the concepts of arguments and parameters in C functions.

Parameters in Function Definition

Parameters are placeholders in a function's definition that represent values to be supplied when the function is called. Here's an example:

#include <stdio.h> // Function definition with parameters void greetPerson(char name[]) { printf("Hello, %s!\n", name); } int main() { // Function call with arguments greetPerson("Alice"); greetPerson("Bob"); return 0; }

In this example, the greetPerson function is defined with a parameter name. When the function is called, the arguments "Alice" and "Bob" are passed, and the %s format specifier is used to print the names.

Function with Multiple Parameters

Functions can have multiple parameters, allowing them to receive more than one input value. Example:

#include <stdio.h> // Function definition with multiple parameters int addNumbers(int a, int b) { return a + b; } int main() { // Function call with arguments int result = addNumbers(5, 3); printf("Sum: %d\n", result); return 0; }

In this example, the addNumbers function takes two parameters (a and b) and returns their sum. When the function is called with arguments 5 and 3, it computes and prints the sum.

Default Values (Not Directly Supported)

C does not directly support default parameter values. However, you can achieve similar functionality by using function overloading or providing a function with multiple parameter sets.

#include <stdio.h> // Function definition with default values int addNumbers(int a, int b) { return a + b; } int addThreeNumbers(int a, int b, int c) { return a + b + c; } int main() { // Function calls with different parameter sets int result1 = addNumbers(5, 3); int result2 = addThreeNumbers(2, 4, 6); printf("Sum 1: %d\n", result1); printf("Sum 2: %d\n", result2); return 0; }

In this example, we have two functions: addNumbers and addThreeNumbers. This mimics the behavior of default values by providing different parameter sets.

Understanding how to work with arguments and parameters is essential for designing flexible and reusable functions in C.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024