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.
#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.
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);
}
}
#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;
elsereturn 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.