I teach C to absolute beginners and I have noticed that some of my students get the notion to use the same name for the function and a local variable in the function. I think it's goofy and would prevent recursion.
Here's an example:
int add2numbers (int a, int b) { /* Tested on Mac OS X with gcc */
int add2numbers = a + b;
return add2numbers;
}
The way I understand how it works is that the variable is in the local scope of the function, and the function is in the global scope.
So, the questions...
Thanks
You cant because if you have example(), 'example' is a pointer to that function. This is the right answer. There are function pointers, which are variables. But also, all function names are treated as const function pointers!
Yes . Local variables overide globals with the same name. Even more, You can have a different variable with the same name inside each scope .
Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures.
A program can have the same name for local and global variables but the value of a local variable inside a function will take preference. For accessing the global variable with same rame, you'll have to use the scope resolution operator.
You are correct in assuming that the function is global and the variable is local. That is the reason why there is no conflict in your program.
Now consider the program given below,
#include<stdio.h>
int x=10;
void x()
{
printf("\n%d",x);
}
int main()
{
x();
return 0;
}
You will get an error because in this program both the function x()
and variable x
are global.
Pascal :)
Simple function in Pascal:
function max(num1, num2: integer): integer;
var
(* local variable declaration *)
result: integer;
begin
if (num1 > num2) then
result := num1
else
result := num2;
max := result;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With