in Programming in C retagged by
348 views
1 vote
1 vote
int fun(int arr[]); int fun(int arr[2]); Both the statements are same??? HELP
in Programming in C retagged by
348 views

1 comment

Compiler breaks either approach to a pointer to the base address of the array, i.e. int* array so passing int array[3] or int array[] or int* array breaks down to the same thing and to access any element of array compiler can find its value stored in location calculated using the formula stated above. This we are passing the array to function in C as pass by reference.

The gist is basically arrays are never passed by value in C, they are always passed as reference:

The 4 declarations below are exactly same :

  1. int fun(int arr[]);  
  2. int fun(int arr[2]);
  3. int fun(int *arr);
  4. int fun(int* arr);

if you pass the size of the array, compiler overlooks the number inside parenthesis

You can read more on : https://www.scaler.com/topics/c/pass-array-to-function-in-c/

0
0

1 Answer

1 vote
1 vote

Declaration is all about just knowing the data type.
It is enough to know that, it is an array of int and it will return int .

So both statements will work same.

Run the below code:




#include <stdio.h>

// Function declaration: int fun(int arr[])
int fun(int arr[])
{
    int sum = 0;
    int i;

    // Calculate the sum of array elements
    for (i = 0; arr[i] != '\0'; i++)
    {
        sum += arr[i];
    }

    return sum;
}

// Function declaration: int fun(int arr[2])
int fun2(int arr[2])
{
    int sum = 0;
    int i;

    // Calculate the sum of array elements
    for (i = 0; arr[i] != '\0'; i++)
    {
        sum += arr[i];
    }

    return sum;
}

int main()
{
    int arr1[] = {1, 2, 3, 4, 5};  // Array of any size
    
    // Call the first function
    int result1 = fun(arr1);
    printf("Result 1: %d\n", result1);

    // Call the second function
    int result2 = fun2(arr1);
    printf("Result 2: %d\n", result2);

    return 0;
}

OUTPUT:

Result1: 15 

Result2: 15

Related questions