Louis B.
Louis B.

Reputation: 517

C Local variable has same name as function - how does it work?

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...

  1. Am I understanding this correctly?
  2. Where the h*** are they getting that idea from?

Thanks

Upvotes: 26

Views: 11855

Answers (3)

Deepu
Deepu

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

user123454321
user123454321

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

Alexey Frunze
Alexey Frunze

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

Related Questions