Home > Mobile >  How to return and have a passby reference in the same function in C
How to return and have a passby reference in the same function in C

Time:12-06

I am looking to optimize the functions below . I have two use cases

  1. I use the written value to print on to output console
  2. I have to fill up a buffer which will sent over CAN

How do I effectively merge these functions into 1

    static float runningrate ;
    void get_rate_CAN(uint16_t* rate) {
        *rate = (uint16_t)truncf(runningrate);
        }
    
    
    uint16_t Getrate(void)
        {
        return (uint16_t)truncf(runningrate);                 
        }
    

CodePudding user response:

You can use the first example for both:

static float runningrate ; //you may want to assign a value here?
void get_rate(uint16_t* rate) {
    *rate = (uint16_t)truncf(runningrate);
}

Examples:

uint16_t *buf = ...;
get_rate(buf);


// equivalent to `uint16_t output = Getrate();` from your original answer:
uint16_t output;
get_rate(&output);
printf("%u", output);

The & operator gets the address of the specified value so that it can be used as a reference.

  • Related