C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Functions
  5. Function Arguments and Return Types

Function Arguments and Return Types

Function arguments are values passed to a function when it is called. These arguments provide input to the function.

  • The values passed are received in the parameters defined in the function.
  • C allows functions with no arguments, fixed arguments, or variable arguments.

The return type of a function determines the type of value the function will return to the calling code.

  • Functions may return values of types like int, float, char, void, etc.
  • If a function returns void, it means it does not return a value.

Example:

#include <stdio.h>

int sum(int a, int b) {  // Function with two arguments and int return type
    return a + b;
}

void greet() {           // Function with no arguments and void return type
    printf("Hello!\n");
}

int main() {
    greet();
    int result = sum(5, 3);
    printf("Sum is: %d\n", result);
    return 0;
}

In C, arrays are passed to functions by reference, meaning only the address of the array is passed.

Syntax:

void displayArray(int arr[], int size);

Example:

#include <stdio.h>

void displayArray(int arr[], int size) {
    for(int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    displayArray(numbers, 5);
    return 0;
}
  • In the example above, numbers is passed to displayArray by reference, and any changes made inside the function affect the original array.

Strings in C are arrays of characters, so they are also passed by reference.

Syntax:

void greet(char name[]);

Example:

#include <stdio.h>

void greet(char name[]) {
    printf("Hello, %s!\n", name);
}

int main() {
    char username[] = "Alice";
    greet(username);
    return 0;
}
  • The string username is passed to greet, which uses %s in printf() to display it.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *