Reputation: 517
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
Upvotes: 26
Views: 11855
Reputation: 7610
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.
Upvotes: 17
Reputation: 1058
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;
Upvotes: 6
Reputation: 62048
1) Am I understanding this correctly?
Pretty much.
2) Where the h*** are they getting that idea from???
Not a constructive question for SO.
Upvotes: 0