LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Local Variables anomaly!! (https://www.linuxquestions.org/questions/programming-9/local-variables-anomaly-796824/)

man s 03-21-2010 05:56 AM

Local Variables anomaly!!
 
I recently came across a piece of code that caught my attention:

main(){

char *s;
char fun();

s=fun();
printf("%s",s);
}
char *fun(){
char buffer[30];
strcpy(buffer,"Hello");
return buffer;
}
Which gives an error: buffer is a local variable and it doesn't exist in main function......
But if I run a code like:

main(){
int i;
i=new_fun();
printf("%d",i);
}

int new_fun(){
int temp;
temp= 10;
return temp;
}

It runs just fine...
Why is the anomaly in both codes present..??

troop 03-21-2010 06:08 AM

The ANSI standard states that main() returns an integer. buffer is not integer.

grail 03-21-2010 07:31 AM

Since arrays are returned by reference, when you return an array you are only returning a reference to it. If the array was declared within the function then its memory would have been released by the time you use its reference outside the function.

I would also point out that your 2 versions of code are not similar as the second is not using arrays

man s 03-21-2010 09:10 PM

Thanx grail...yeah I almost got it..But are integers by default returned by value?...doesn't it always involve the overhead of extra memory space..??

paulsm4 03-22-2010 01:22 AM

Hi -

Code:

#include <stdio.h>

int
myfunc (int a)
{
  return a + 2;
}

int
main (int argc, char *argv[])
{
  printf ("myfunc(2)= %d\n", myfunc (2));
  return 0;
}

As you can guess, this function will return "4".

Parameter "a" was definitely "passed by value" ...
... and function "myfunc()" definitely returns an "int" ...
... but I wouldn't see the value 4 was "returned by value". I'd merely say "function 'myfunc ()' returned an int".

PS:
This applies equally to C and C++.

The big differences here are:
1) C++ absolutely *requires* you to specify the return value type (or specify "void" if there is *no* return value), classic "C" would default to "return int". You should *always* explicitly declare your return value, in *both* C and C++. Whether you get a compile error or not :)

2) C++ would allow either/both the parameter and/or return value to be a reference ("&"). C doesn't support references (at least not the last time I looked). Pointers: yes. References: no.

'Hope that helps .. PSM

PPS:
No, there's no "extra memory space". An integer return value is usually copied to a register (for example, "eax" for an Intel CPU).


All times are GMT -5. The time now is 12:11 AM.