saving . . . saved Function return has been deleted. Function return has been hidden .
Function return
Title
Question
How function can return a value without writing return statement in its definition?help me out pls

C-and-Cpp Functions 03-04 min 40-50 sec 29-02-20, 12:02 p.m. HarryKaur

Answers:

A function (whose return type is NOT void), has to return something of the appropriate return type (e.g. int) using a return statement.  Otherwise the compiler will show an error.
29-02-20, 12:11 p.m. bhaskar76
but my function is giving answer without even writing a return value.
29-02-20, 12:35 p.m. HarryKaur
#include <stdio.h>
int square(int n)
{
   int s;
   s=n*n;
}
int  main()
{
   int m,r;
   scanf("%d",&m);
   r =square(m);
   printf("Square of number = %d",r);
   return 0;
}

29-02-20, 12:36 p.m. HarryKaur
Yes .. but the program typed in the videos, 
int add(int a,int b)
{
     int c = a + b;
}
int main()
{
   int sum;
   sum = add(5,4);
   printf("Sum of a and b is %d\\n",sum);
   return 0;
}



there is no return statement in the add(), still the sum is displayed correctly in the video.
hows it possible ?
29-02-20, 12:36 p.m. bles
Because when you don't write return statement it will return latest Accumulator (AL) value as a return value.
29-02-20, 2:28 p.m. kapilshukla2006

Login to add comment


This is possible with two different techniques.
1) Using Global Variable and
2) Using Pass by Address Method

Example-1:
int k;
void increment();
int main()
{
increment();
printf("%d",k);
return 0;
}

void increment()
{
k=k+1;
}

Example-2:

void increment(int *);

int main()
{
int k=5;
increment(&k);
printf("%d",k);
return 0;
}

void increment(int *p)
{
*p = *p + 1;
}
29-02-20, 12:16 p.m. kapilshukla2006
I am using neither of these ways but still it is working

#include <stdio.h>
int square(int n)
{
   int s;
   s=n*n;
}
int  main()
{
   int m,r;
   scanf("%d",&m);
   r =square(m);
   printf("Square of number = %d",r);
   return 0;
}

29-02-20, 12:58 p.m. HarryKaur
Yes, True but it return the last used parameter value (value in AL).
So your functions return type and parameters must be matched accordingly.
like
int test(int p,int q, int r)
{
 int a,b,c;
a=p;
b=q;
c=r;
}

called like:
test(1,2,3);

it will return 3.
29-02-20, 2:23 p.m. kapilshukla2006

Login to add comment


Log-in to answer to this question.