//表达式#include<stdio.h>intabb(int c,int d){return c + d;//return 表达式;}intmain(){int a =0;int b =0;scanf_s("%d %d",&a,&b);int f =abb(a,b);printf("%d", f);return0;}
#include<stdio.h>voidmyFunction(){printf("Before return statement.\n");// 如果满足某种条件,函数提前返回 if(1==1){// 这个条件总是为真 printf("This will be printed because the condition is true.\n");return;// 执行return语句,函数立即返回 }// 下面的代码将不会被执行,因为return语句已经执行了 printf("This will not be printed.\n");}intmain(){myFunction();// 调用函数 printf("Back in main function.\n");return0;}
结果为:
Before return statement.
This will be printed because the condition is true.
Back in main function.
4. 如果函数中存在if等分⽀的语句,则要保证每种情况下都有return返回,否则会出现编译错误。
例子1:
#include<stdio.h>intmyFunction(int value){if(value >0){printf("Value is positive.\n");return value;// 当value大于0时,返回value }// 当value小于等于0时,缺少return语句 }intmain(){int result =myFunction(-5);// 调用函数并尝试获取返回值 printf("Result: %d\n", result);// 使用返回值 return0;}
结果为:
Result: 1
例子2
#include<stido.h>//判断⼀年是不是闰年intis_leap_year(int y){if(((y%4==0)&&(y%100!=0))||(y%400==0))return1;elsereturn0;}intmain(){int y =0;scanf("%d",&y);int r =is_leap_year(y);if(r ==1)printf("闰年\n");elseprintf("⾮闰年\n");return0;}