Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

scope

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

like image 466
Louis B. Avatar asked Apr 25 '13 13:04

Louis B.


People also ask

Can variable name same as function name in C?

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!

Can we declare local variables with same name in different functions?

Yes . Local variables overide globals with the same name. Even more, You can have a different variable with the same name inside each scope .

Can you have functions with the same name in C?

Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures.

Can a function have a local variable with the same name as a global variable?

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.


2 Answers

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.

like image 151
Deepu Avatar answered Oct 12 '22 08:10

Deepu


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;
like image 38
user123454321 Avatar answered Oct 12 '22 08:10

user123454321