cpass-by-referencekernighan-and-ritchiecall-by-value

Is this call by reference or by value in C?


I'm reading a book the c programming language authored by Brian W. Kernighan and Dennis M. Ritchie.

The book lists code below

void strcpy(char *s, char *t){
    while((*s = *t) != '\0'){
        s++;
        t++;
    }
}

and says:

Because arguments are passed by value, strcpy can use the parameters s and t in any way it pleases

which I'm not agreed with. Why above arguments are passed by value?

According to another book C how to program:

In C, you use pointers and the indirection operator to simulate call-by reference. When calling a function with arguments that should be modified, the addresses of the arguments are passed.

In latter point of view, it's definitely call-by-reference.

Please tell me which way is correct and why, thanks!

btw, after assignment *s = *t, which one is compared with '\0'? *s or *t?


Solution

  • C passes arguments by value, always, meaning that the called function receives a local copy of whatever the caller refers to.

    The called function can modify the received value, because it is a local copy, without affecting the original value. For example:

    char *test(char *s) {
      s++;
      return s;
    }
    
    t = test("A");
    

    it's legal and shows that the parameter s can be modified without affecting the caller (which passes a literal...).

    But the strcpy() of you example does something different: it takes a pointer s, and modifies what s points to. Pointers are powerful, and they can be used to simulate "pass by reference" (a pointer is a reference).

    after assignment *s = *t is held, which one is compared with '\0'? *s or *t?

    The *s: in C, an assignment returns a value - and the value is the value of the assigned variable after the assignment is done. Writing:

    if (i=3) ...
    

    is the same as

    i=3;
    if (i) ...
    

    If i was a pointer the syntax would be different but the mechanism is the same, the assignment would "use" the pointer and the value of the whole assignment is used as expression to be evaluated in the test.