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..?? |
The ANSI standard states that main() returns an integer. buffer is not integer.
|
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 |
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..??
|
Hi -
Code:
#include <stdio.h> 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. |