retagged by
945 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.

retagged by

2 Answers

Best answer
3 votes
3 votes
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 votes
1 votes
                #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

Related questions

3 votes
3 votes
2 answers
1
sunil sarode asked Nov 4, 2017
2,132 views
Choose the False statements:(a) The scope of a macro definition need not be the entire program(b) The scope of a macro definition extends from the point of definition to ...
4 votes
4 votes
2 answers
3
Dexter asked Apr 12, 2016
2,019 views
1 votes
1 votes
1 answer
4