RETURN

I am a beginner and all help will be fine. I was trying to learn what "return" does and I did 2 func (one of with return, one of without return) but 2 of them works right. Can anyone tell me what return does? Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <stdio.h>	

int topla(int x, int y)
{
	int toplam=x+y;
	return toplam;
	
}

int carp(int s1, int s2)
{
	int carpim=s1*s2;
	
}

int main()
{
	int a,b;
	printf("2 sayi giriniz : ");
	scanf("%d%d",&a, &b);
	printf("%d\n",topla(a,b));
	printf("%d",carp(a,b));
}
You need the return statement otherwise you can't be sure what value you will get back from the function.

You are just lucky if you get the correct value. When I compile your program with GCC 4.9.2 I get different outputs. If I compile without optimizations (-O0) it prints the value of b and if I compile with optimizations (-O2) it always prints 0.
Last edited on
Is it check system or something?
What about if you do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int carp(int s1, int s2)
{
	int carpim=s1*s2;
	printf("Hello\n");
	
}

int main()
{
	int a = 7, b = 5;

	printf("%d",carp(a,b));
}


I get different results with different compilers, but don't get 35 at all.
As Peter87 said, you are just lucky if you get the correct value.
You can also use return to exit early from function.
Something like:
1
2
3
4
5
6
7
int calc(int x, int y) {
    int z;
    printf("If you don't want to calculate sum enter 0: ");
    scanf("%d", &z);
    if (z == 0) return -1; // "I don't want to execute rest of code, just return -1"
    return x + y;
}


If your function is void you can use return; for the same purpose:
1
2
3
4
5
6
7
void calc(int x, int y) {
    int z;
    printf("If you don't want to calculate sum enter 0: ");
    scanf("%d", &z);
    if (z == 0) return; // "I don't want to execute rest of code, break here"
    printf("%d", x + y);
}


Note that this is equivalent to:
1
2
3
4
5
6
7
8
void calc(int x, int y) {
    int z;
    printf("If you don't want to calculate sum enter 0: ");
    scanf("%d", &z);
    if (z != 0) {
        printf("%d", x + y);
    }
}
I was studying return again and my head confused. How can system know that return 1 and 0 where they go?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>

int leap_year(int); /* function's prototype */

int main()
{
  int year;

  printf("Enter a year: ");
  scanf("%d",&year);

  if( leap_year(year) ) 
      printf("%d is a leap year\n",year);
  else
      printf("%d is not a leap year\n",year);
}


int leap_year(int year)
{
  if(  year % 4   == 0 &&
       year % 100 != 0 ||
       year % 400 == 0  ) return 1;
  else return 0;
}
They go back to where they were called from. If 1 is returned, the if statement will take it as "true" and "is a leap year" will be outputted. If the return is 0, it the if statement will be false.
Topic archived. No new replies allowed.