in Programming in C retagged by
991 views
0 votes
0 votes

The following program runs perfectly fine without showing compilation error. I am unable to understand why as 'c' is a local variable of 'function_addition'. So, shouldn't it throw an error?

#include<stdio.h>

int function_addition(int a, int b)
{
int c;
c = 10;
return c;
}
int main()
{ //function_addition(13, 15);
printf("%d", function_addition(13,15) );
}

Also, another similar program involving strings(see below) throws an error when we try to print it in a similar way.

#include<stdio.h>
char *getstring(){
char str[]="GateOverflow";
return str;
}
int main()
{
printf("%s", getstring());
}// Gives error

Please explain me this ambiguity as to why the first one prints the value of c correctly whereas the second program shows an error.

in Programming in C retagged by
991 views

2 Answers

3 votes
3 votes
Best answer
Here the difference is the first program returning value not address.In the first program, you are just returning the value of C and not the address it is printing the value.

In the second program, you are returning address of str which is vanished once you come out of the function.So it is giving an exception when trying to print it.

PS: Accessing a local variable outside the scope is undefined behaviour -- we may not always get a segmentation fault here.
edited by
1 vote
1 vote
                #include<stdio.h>
                #include<string.h>
                char *getstring(){
                char *str="GateOverflow";// here the program is giving error . Array value cannot be return through pointer
                return str;
                }
                int main()
                {
                printf("%s", getstring());
                }

In 1st program c is a local variable and After  returning c value in main() , it simply prints the value.

But in 2nd program ,it takes the value in an array. And returning it in main() with a pointer. As address of array is constant, returning through pointer giving the error

4 Comments

https://gateoverflow.in/3466/gate2007-it-33

In this program value also copied , but not back to main() function.

So, why in this given program value is copied back.

Can u plz point out, where my fault is?

0
0
That is NOT C language and pass by reference is given in the question.
1
1

Actually I tried with some varity in this program.Still not getting satisfactory result. Each time there is a variety in output. If we  " return an array address as a pointer " in a function to a pointer , it will give runtime error

https://ideone.com/kIKZOc

0
0

Related questions

4 votes
4 votes
2 answers
3
Dexter asked in Compiler Design Apr 12, 2016
2,085 views
Dexter asked in Compiler Design Apr 12, 2016
by Dexter
2.1k views