[Cs3] Efficiency question
Mikhail Nesterenko
mikhail at cs.kent.edu
Sun Mar 2 09:05:26 EST 2014
> Professor, while looking at your example in changing an element of an
> array, you give this example:
>
> int* getElement(int x[], int i) {
> return &x[i];
> }
>
> int main(void){
> int a[] = {10,20,30};
>
> cout << *getElement(a, 1);
> *getElement(a, 2) = 55;
> cout << *getElement(a,2);
> }
>
> However, is the method for changing the element any better than simply
> doing this?
>
> int main(void){
> int a[] = { 10, 20, 30 };
>
> cout << a[1];
> a[2] = 55;
> cout << a[2];
> }
>
>
> The only instance I can think of when the first example is necessary is
> when you have an array as a private inside of a class. Is one better than
> the other in terms of efficiency, functionality, or of the like?
The example was not to demonstrate efficiency but the usage of
pointers and (in a similar example) references. In the above case, it
is shown that a function may return a pointer and this pointer
(dereference) may be used as an l-value (on the left-hand-side of the
assignment operator).
In general, the overhead of a function call is a few arithmetic
instructions plus whatever is necessary to handle parameter
passing. So, with few exceptions, code clarity and flexibility comes
ahead of minor efficiency savings.
Thanks,
--
Mikhail
More information about the cs3
mailing list