:: Re: [DNG] Studying C as told. (For …
Góra strony
Delete this message
Reply to this message
Autor: Irrwahn
Data:  
Dla: dng
Temat: Re: [DNG] Studying C as told. (For help)
On Wed, 22 Jun 2016 11:15:44 +0200, Edward Bartolo wrote:
> I learnt arrays are always passed by reference to function calls. So,


KatolaZ already posted a very clear and correct comment
regarding by-reference vs. by-value, but anyway:

It is a fact that there are no *references* in C, but only
values. However, such values can very well be pointers
*referring* to objects. I suspect that missing that
apparently small but nevertheless _extremely_ important
difference in semantics may have lead to the misconception.

> I wrote the following program to make use of this so that a variable
> in main() is modified in a function call.
>
> Is this technique used?
>
> The program:
> --------------------------
> #include <stdio.h>
>
> void times2(int i[]) {


Note that "int i[]" and "int *i" are synonymous — despite 
the difference in syntax they have absolutely identical 
meaning. The bracket notation conventionally is not used 
very often. Sometimes it is used as an explicit hint to the 
reader that the value to be passed is not only a pointer, 
but a pointer to the first element of an array. Compare: 
     int main( int argc, char **argv )
vs.
     int main( int argc, char *argv[] )


Both lines have identical meaning, but the second form gives
away some supplementary information to the human(!) reader.


> i[0] = 33;


The array bracket notation in C is nothing but syntactic
sugar covering up the fact that array subscription is just
plain old pointer arithmetic:

arr[idx] <==> *(arr+idx)

Consequently, your line above is identical to (and in your 
example program better be written as): 
    *i = 33;



Conclusion: While your code wasn't exactly wrong, it could
have been slightly confusing to the unsuspecting reader.

HTH, Regards
Urban