Home > other >  Function parameters in c
Function parameters in c

Time:07-04

Are function parameters real variables or are they variables that store another variable or what even are they exactly at this point. Pointer parameters are included too. If you put & in the argument then why do you even need to declare pointer parameter in the function if you already got the memory address with &? Does the pointer parameter actually store memory address afterall or not?

CodePudding user response:

You may want to watch a video explaining how pointer parameters to functions work: https://www.youtube.com/watch?v=LW8Rfh6TzGg

But let me answer your specific questions...

Are function parameters real variables

Yes. But their scope is the body of the function; and their lifetimes are during invocations of the function: They come into existence when the function begins execution, and cease to exist when you return from the function.

or are they variables that store another variable

Variables can't store variables. Variables store values. (Pointer variables' values happen to be addresses.)

Pointer parameters are included too. If you put & in the argument then why do you even need to declare pointer parameter in the function if you already got the memory address with &?

Suppose you have a variable int x. Now, x is an integer, but &x is a pointer-to-an-integer - the address of the x variable.

In C, you can't define a parameter and have it represent a different variable elsewhere. What you can do is a pass an address of an external variable, then go through the address to read or write the value of that variable.

Does the pointer parameter actually store memory address after all or not?

It does actually store an address.

CodePudding user response:

Are function parameters real variables

Yes. Inside a function, a parameter acts just like a local variable (that was initialized to the passed-in value at the top of the function).

i.e.

void foo(int a)
{
   [...]
}

is logically equivalent to this (pseudocode):

void foo(...)
{
   int a = /* the value that the caller called foo() with */
   [...]
}

If you put & in the argument then why do you even need to declare pointer parameter in the function if you already got the memory address with &?

Placing & in the argument allows you to pass a pointer to the value, rather than passing the value itself.

If you want to pass a pointer, then your function needs to accept a pointer type as its argument, otherwise your call to the function won't compile.

Does the pointer parameter actually store memory address afterall or not?

Yes, it does.

  • Related