26

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

4
  • 13
    +1 for those kids! Never thought about it!! XD Commented Apr 25, 2013 at 14:01
  • 5
    1) You are correct. 2) Pascal? Commented Apr 25, 2013 at 14:03
  • 4
    Assigning to a variable named the same as the function, isn't that how to return values in Pascal and Basic? Commented Apr 25, 2013 at 14:03
  • 1
    Thanks for those comments. I'm considering this question answered. And to Biniyaka, yes, they can get really creative :)
    – Louis B.
    Commented Apr 25, 2013 at 15:01

3 Answers 3

17

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.

1
  • 1
    Exactly. Yet, if they declare a local var inside function x(), the local var would "hide" anything in the global scope. Thanks for the comment.
    – Louis B.
    Commented Apr 25, 2013 at 14:31
6

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;
2
  • 6
    ah, things forgotten for a reason. what an ugly language. +1 Commented Apr 25, 2013 at 14:16
  • 1
    Thanks! Now my question (OK it's not really a question) is where the h*** did non-programmers learn Pascal???
    – Louis B.
    Commented Apr 25, 2013 at 14:34
0

1) Am I understanding this correctly?

Pretty much.

2) Where the h*** are they getting that idea from???

Not a constructive question for SO.

1
  • 2
    Agree on (2). Not so much a question as an expression of frustration. Thanks.
    – Louis B.
    Commented Apr 25, 2013 at 14:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.