文章目录
- main()
- main的参数
- main的返回值
- 递归的main
- 替换main
- 起点?
- main函数三种写法
- 编译器
- Debug调试
- 未定义行为 (Undefined behavior)
- 编译、链接、运行
main()
main函数也是函数,也有返回值、形参,也能递归调用等等等
main的参数
#incldue <stdio.h>
int main(int argc, char* argv[]) {
for(int i = 0; i < argc; i ++) {
printf("arg%d : %s", i, argv[i]);
}
return 0;
}
/*
rm arg
make arg
*/
main的返回值
递归的main
#include <stdio.h>
int a = 1;
int b = 1;
int temp = 0;
int main(void) {
if(b < 500) {
temp = b;
b += a;
a = temp;
printf("b = %d\n", b);
main();
}
return 0;
}
/*
rm recursion
make recursion
*/
替换main
#include <stdio.h>
#include <stdlib.h>
int main(int a, int b) {
return a + b;
}
int myfun(void) {
printf("hello\n");
int a = main(1,1);
printf("a = %d\n", a);
exit(0);
}
/*
rm main
make main
*/
起点?
main函数三种写法
int main(void) {}
int main(int argc, char* argv[]) {} /* 当然argc和argv是可以改成别的名字的*/
main() {} //不推荐
int main() {} //不推荐
编译器
c89
c2x
但是不同编译器会对C语言标准进行拓展,比如增加一些“特性”或者关键词。
- clang
特征检查宏,_Nullable和_Nonnull,函数重载,Blocks语法 - gcc
零长数组,语句表达式,内建函数,__attribute__属性,范围case - Keil C51
data, code, bit, sbit, sfr, reentrant
Debug调试
#include <stdio.h>
int main(void) {
printf("hello");
while(1);
return 0;
}
#include <stdio.h>
void copy(char*, char*);
int main(void) {
char string1[10] = "hello";
char string2[256] = "some words in string2";
char string3[256] = "world \nPS : string1 will get \"world\" and string2 stay still";
copy(string1, string3);
printf("%s\n\n\n%s",string1,string2);
return 0;
}
void copy(char* s1, char* s2) {
for(unsigned char i = strlen(s1); i >= 0; i--) {
s1[i] = s2[i];
}
return ;
}
#include <stdio.h>
int main(void) {
int year = 0;
if(year % 4 = 0)
if(year % 100 != 0)
printf("yes\n");
else
printf("no\n");
return 0;
}
#include <stdio.h>
int main(void) {
int n;
char* string;
scanf("%d", &n);
string = (int*)malloc();
}
#include <stdio.h>
#include <stdlib.h>
void fun(void);
int main() {
while(1) {
fun();
}
return 0;
}
void fun(void) {
char* buf = (char*)malloc(512);
int key_value = 0;
scanf("%d", &key_value);
switch(key_value) {
case 1 ... 5:
/* deal with something */
free(buf);
return ;
default :
printf("error key num\n");
return ;
}
}
未定义行为 (Undefined behavior)
对于相同的程序,不同的编译环境、编译器编译出来的结果也不一定相同。
这叫未指定行为 (Unspecified behavior)
程序行为并未在 语言规范 (在 C 中,自然是 ISO/IEC 9899 一类的规格) 所明确定义规范。缩写为 “UB”。
undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres.
- 数组越界
- 解引用空指针
- 未初始化的局部变量
- 除以零
- 符号溢出
- 位移操作数太大