I was asked in an interview :
What is the scope of the parameters that are passed to a function inside the function?
Sometimes interviewers don't actually know what they're talking about,
and sometimes they do but their question is misunderstood... Parameters
aren't passed to a function. Arguments are passed to a function.
Roughly speaking, the values of the arguments become the initial values
of the parameters.
To answer your question, the scope of a function's parameters depends on
whether or not the function declaration is a function definition or not.
If it's a declaration, the parameters have what's called "function
prototype scope". For example:
int add(int a, int b);
This is not a definition, so 'a' and 'b' have function prototype scope.
For ex : int add (int a, int b)
{
return (a+b);
}
This is a function definition, so 'a' and 'b' have what's called "block
scope".
here, what is the scope of a & b inside the functions ?
'a' can be used anywhere after the 'a' in 'int a' and anywhere before
the function's final '}'. 'b' can be used anywhere after the 'b' in
'int b' and anywhere before the function's final '}'. Because both
identifiers' scopes end at the same place, they are said to have the
"same scope".
I got confused with passing by value and passing by reference. Can anyone please clarify ?
This is a completely separate subject than your earlier questions. As
someone else already answered, C does not have "pass by reference". As
mentioned above, in C, you pass arguments whose values become the
initial values for the function's parameters.
Caller: Has arguments
Callee (called function): Has parameters
The two are _separate_. The called function can modify its parameters
and those modifications _do_not_ modify the caller's arguments. For
example:
void foo(void) {
int x = add(21, 21);
}
Your 'add' function above cannot modify the arguments '21' and '21'. It
can only modify its parameters 'a' and 'b'. As another example:
void bar(void) {
int i = 21;
int j = 21;
int x = add(i, j);
}
Your 'add' function above cannot modify the arguments 'i' and 'j'. It
can only modify its parameters 'a' and 'b'.