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 ?

2
  • 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 Commented Aug 16, 2020 at 18:38
  • Several people mentioned it in this thread. You have links there to the official C documentation. Commented Aug 16, 2020 at 19:34

2 Answers 2

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".

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.