user133466
user133466

Reputation: 3415

Arrays vs Local variables in C Programming

The following code is trying to make a point (probably the difference between arrays and local variables) I only have a vague idea on the code. Would someone please elaborate? Thanks

void doit(int x[10], int y) {
    y = 30;
    x[0] = 50;
}

void main(void) {
    int x[10];
    int y = 3;
    x[0] = 5;
    printf("x[0] is %d and y is %d\n", x[0], y);
    doit(x, y);
    printf("x[0] is %d and y is %d\n", x[0], y);

}

Upvotes: 0

Views: 1532

Answers (4)

Daniel Pryden
Daniel Pryden

Reputation: 60947

In C, all arguments are passed by value. However, arrays decay into a pointer to the first element to the array when they get passed; the result is effectively as if the array was passed by reference.

In your code, the doit() function can mutate the array pointed to by x, but it cannot mutate the simple int value in y.

Upvotes: 3

jdehaan
jdehaan

Reputation: 19928

y is passed by value meaning that a temporary copy is created, you have to pass it as a pointer to modify it:

void doit(int x[10], int* y) {
    *y = 30;
    x[0] = 50;
}

Declaring an array is also not really needed. The compiler anyway understands only that it is a pointer and does (usually) not check the boundaries.

void doit(int* x, int* y) {
    *y = 30;
    x[0] = 50;
}

Upvotes: 1

Gopi
Gopi

Reputation: 5877

Local variables are passed as value where as in arrays the reference is passed not the actual values. so when you change the value in child array the parent array will get changed. Arrays are same as pointers in using the reference

Upvotes: 0

caf
caf

Reputation: 239011

It is showing that arrays are not really passed directly to functions - instead, the address of the first member of the array is passed.

That means that if the called function modifies the array that was "passed", it is modifying the original array in the caller.

On the other hand, when the called function modifies the plain int parameter y, it is modifying a local copy of the variable, and the change is not reflected in the caller.

Upvotes: 4

Related Questions