0

I was wondering which of these three methods is faster and better optimized (in C) considering that myFunc() will be called multiple times and that the variable will be compared and changed:

1 - Creating every time a new variable:

char myFunc( void ) {
    char c;
    // code
    return c;
}

2 - Passing a pointer as argument:

void myFunc( char *_ptrC ) {
    // code (no need for return since _ptrC is a pointer)
}

3 - Passing a variable and returning it:

char myFunc( char _c ) {
    // code
    return _c;
}
isGonzito
  • 27
  • 7
  • 1
    It's up to the compiler what code is generated. The C standard does not dictate that. – klutt Nov 19 '22 at 17:07
  • Sorry, I marked this as a duplicate and provided a wrong link. Anyway - there's plenty of information about this topic here at SO. Also, it highly depends on your code and compiler optimizations - in some cases stack operations are performance wise same as operating with pointers. – Andrejs Cainikovs Nov 19 '22 at 17:11
  • 1
    Which is "best" depends very much on use-case and other external factors. There's no single "this is best anytime" answer. – Some programmer dude Nov 19 '22 at 17:14
  • @AndrejsCainikovs *`in some cases stack operations are performance wise same as operating with pointers.`* ??? – 0___________ Nov 19 '22 at 17:18
  • @AndrejsCainikovs you did not close it only klutt. You need C badge to do it on your own – 0___________ Nov 19 '22 at 17:19
  • @0___________ You surprised about what? I wrote - it depends, and also wrote - in some cases. If you take this particular example, compile it with default optimizations, and disassemble it - I'm really not sure there will be much of a difference. – Andrejs Cainikovs Nov 19 '22 at 17:26
  • Of course, adding more logic, etc, most likely will show better performance when using pointers vs variables. – Andrejs Cainikovs Nov 19 '22 at 17:32

0 Answers0