一 goto语句
#include<stdio.h>
int main()
{
again:
printf("hehe\n");
printf("haha\n");
goto again;//跳到again的位置,必须在同一个函数内
return 0;
}
理论上讲goto语句没必要,可以被循环代替,但某些场合下goto语句用得着,例如跳出多层循环
for(...)
{
for(...)
{
for(...)
{
if(disaster)
goto error;
}
}
}
error:
if(disaster)
用goto制作关机程序(程序启动后,60秒后关机,60秒内输入:取消,就可以取消关机
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//关机命令:shutdown -s -t 60
//取消关机命令:shutdown -a
//库函数--执行系统命令
int main()
{
char input[20]={0};
system("shutdown -s -t 60");
again:
printf("请注意,你的电脑在1分钟后关机,输入“取消”,取消关机\n");
scanf("%s",input);
if(strcmp(input,"取消")==0)
{
system("shutdown -a");
}
else
{
goto again;
}
return 0;
}
二 函数
1 库函数
MSDN能查到库函数的用法与头文件
strcpy函数
char *strcpy(char *dest,const char *src); 把src所指向的字符串复制到dest
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[20]={0}; //目的地
char arr2[]="HELLO";//源数据
strcpy(arr1,arr2);
printf("%s\n",arr1);
return 0;
}
memset函数
void *memset(void *s,int ch,zise_t n); 将s中当前位置后面的n个字节用ch替代并返回s
#include<stdio.h>
#include<string.h>
int main()
{
char arr[]="hello world";
memset(arr,'x',5);
printf("%s",arr);
return 0;
}
2 自定义函数
自定义函数的函数名,返回值,函数参数要我们自己设计
#include<stdio.h>
int get_max(int x,int y)//函数定义
{
int z=0;
z=(x>y?x:y);
return z;
}
int main()
{
int a=0;
int b=0;
scanf("%d %d",&a,&b);
int m=get_max(a,b);//函数调用
printf("%d\n",m);
}
有的函数也无需返回值和参数
#include<stdio.h>
void menu()
{
printf("****************\n");
printf("**** 1.play ****\n");
printf("**** 0.exit ****\n");
printf("****************\n");
}
int main()
{
menu();
return 0;
}
3 函数的参数
实参:函数调用时的参数
形参:函数定义时的参数,调用后销毁
函数调用的实参可以是变量,常量,表达式,函数
4 函数的调用
Swap1(a,b); //传值调用
Swap2(&a,&b);//传址调用
传值调用:对形参的修改不会影响实参
传址调用:让函数与函数外部变量建立联系,函数内部能直接操作函数外部变量
交换两个整型变量内容
错误代码:
#include<stdio.h>
void Swap1(int x,int y)
{
int z=0;
z=x;
x=y;
y=z;
}
int main()
{
int a=0;
int b=0;
scanf("%d %d",&a,&b);
printf("交换前a=%d b=%d\n",a,b);
Swap1(a,b);
printf("交换后a=%d b=%d\n",a,b);
return 0;
}
正确代码:
#include<stdio.h>
void Swap2(int *x,int *y)
{
int z=0;
z=*x;
*x=*y;
*y=z;
}
int main()
{
int a=0;
int b=0;
scanf("%d %d",&a,&b);
printf("交换前a=%d b=%d\n",a,b);
Swap2(&a,&b);
printf("交换后a=%d b=%d\n",a,b);
return 0;
}
a b是实参,x y是形参,当函数调用时,实参传给形参,形参其实是实参的一份临时拷贝,对形参的修改不会影响实参