- Is there a performance benefit by passing ints by reference rather than by value ? I say this because if you pass by reference you are creating a 4-byte pointer but if you pass by value you are creating a 4-byte copy of the value anyway. So they both occupy an extra 4-bytes, right ?
-
Is it possible to pass an int literal by reference using a cast: (int *) ? Or do you have to pass a pointer to an int ? See example code below:
int func1(int *a){ (*a)++; // edited from comment by Joachim Pileborg printf("%i\n", *a); return 0; } int func2(int a){ a++; printf("%i\n", a); return 0; } int main(void){ func1(&(int *)5); // an int literal passed by reference using a cast ? func2(5); return 0; }
Is there a performance benefit by passing ints by reference rather than by value
Share
The benefit of passing-by-pointer (there are no references in C) is that a function may update the original
int, i.e. return a value in it. There is no performance benefit; rather, passing-by-pointer may slow your program down because theintthat is pointed to has to be in addressable memory, so it can’t be in a register.Note that
&(int *)5does not do what you think it does.(int *)5casts the value5to a pointer, interpreting it as a memory address. The&would give that pointer’s address, except that taking the address of a temporary is illegal. You probably meant