1

I wanted to replace below switch case statement with following code

switch (n)
  {
      case 0:
            i2c_scan();
            break;
        case 1:
            i2c_read(45);
            break;
        case 2:
            i2c_write(45,5);
            break;
        default:
            printf("\nwrong input\n");
            break;
  }

Please check following code

#include<stdio.h>

void i2c_scan()
{
    printf("\ni2c scan\n");
}
void i2c_read(int x)
{
    x= x+1;
   printf("\ni2c read: %d\n",x); 
}
void i2c_write(int x , int y)
{
    x=x+y;
    printf("\ni2c write:%d\n",x);
}

int main() {
   int n;
   
void (*fun_ptr_arr[])() = {i2c_scan,i2c_read,i2c_write}; 
    (*fun_ptr_arr[0])(45,5);  //have put array index to show results ,i could have took input from user and put it here like switch case: case number) 
    (*fun_ptr_arr[1])(45,5);
    (*fun_ptr_arr[2])(45,5);
    
}

Output:

i2c scan

i2c read: 46

i2c write:50

How above code is compiling and running without any error when i am passing more arguments then required to the function ? And how is it working correctly like i2c_read takes first argument and gives result ?

G.ONE
  • 507
  • 1
  • 5
  • 14
  • 2
    Passing more or less arguments to a C function is considered undefined behaviour. If you really want to pass a variable number of arguments to a function you should have a look at [variadic functions](https://www.gnu.org/software/libc/manual/html_node/Variadic-Functions.html) – DanBrezeanu Aug 16 '20 at 18:38
  • Several people mentioned it in [this](https://stackoverflow.com/questions/17104787/passing-more-than-required-arguments-to-c-function) thread. You have links there to the official C documentation. – DanBrezeanu Aug 16 '20 at 19:34

2 Answers2

0

How above code is compiling and running without any error when i am passing more arguments then required to the function ?

As @DanBrezeanu wells points out, the behavior is UB.
Anything may happen including apparently "working correctly".

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

The declaration

void (*fun_ptr_arr[])()

Means that fun_ptr_arr is an array of pointers to functions of the form:

void f() { ... }
void g() { ... }

and that is different from:

void f(void) { ... }
void g(void) { ... }

This answer elaborates more, but the gist is: the second form is a function that accepts no arguments, whereas the first form accepts any number of arguments.

root
  • 5,528
  • 1
  • 7
  • 15