C語言main函數的寫法
標準中,只有下面兩種寫法:
int main (void) { /**body**/ }
以及
int main (int argc, char *argv[]) { /**body**/ }
而C++的第二種與C類似,第一種是這樣的:
int main () { /**body**/ }
參考《C語言的main函數到底該怎麼寫》
如果沒有返回類型
#include<stdio.h>
test()
{
printf("https://www.yanbinghu.com\n");
}
int main(void)
{
test();
return 0;
}
它會默認爲int
$ gcc -o test test.c
test.c:2:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
test()
^
注意,使用函數前一定要聲明,對於沒有聲明,而試圖使用,可能會錯將int用成其他類型,導致災難。參考《記64位地址截斷引發的掛死問題》
如果main函數沒有return
#include<stdio.h>
int main(void)
{
printf("lalalala\n");
}
編譯器一般都會幫你在最後加上return 0。
結構體成員賦值
結構體裏還有結構體,你還一個一個成員的複製?
//來源:公衆號編程珠璣
//https://www.yanbinghu.com
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Info_t0
{
int a;
int b;
char str[128];
};
struct Info_t
{
struct Info_t0 c;
int d;
};
int main(void)
{
struct Info_t *test = malloc(sizeof(struct Info_t));
memset(test,0,sizeof(struct Info_t));
test->c.a = 10;
test->c.b = 24;
strncpy(test->c.str,"https://www.yanbinghu.com",sizeof("https://www.yanbinghu.com"));
test->d = 10;
struct Info_t test1;
test1.c = test->c;//成員直接賦值,完成拷貝
free(test);
test = NULL;
printf("test1.c.a = %d,test1.c.b = %d test1.c.str = %s\n",test1.c.a ,test1.c.b,test1.c.str);
return 0;
}
輸出結果:
test1.c.a = 10,test1.c.b = 24 test1.c.str = https://www.yanbinghu.com
打印字符串不檢查空
打印字符串時,沒有結束位置是致命的!
//來源:公衆號編程珠璣
//https://www.yanbinghu.com
#include<stdio.h>
int main(void)
{
char *p = NULL;
printf("%s\n",p);//災難!
char arr[] = {'h','e','l','l','o'};
printf("%s\n",arr);//災難!
return 0;
}
參考《NULL,0,'\0'的區別》和《你可能不知道的printf》。
輸出百分號
//來源:公衆號編程珠璣
//https://www.yanbinghu.com
#include<stdio.h>
int main(void)
{
printf("%%\n");//輸出%號
return 0;
}
代碼太長換行
#include <stdio.h>
#define TEST "https://www.yan\
binghu.com"
int main()
{
printf("Hello World %s\n",TEST);
return 0;
}
判斷兩數之和是否超出範圍
相關文章《C語言入坑指南-整型的隱式轉換與溢出》。
//來源:公衆號【編程珠璣】
#include <stdio.h>
#include <limits.h>
int main()
{
int a = INT_MAX - 10;
int b = INT_MAX - 20;
//if(a + b > INT_MAX),不能這樣做
if(a > INT_MAX - b)
printf("a + b > INT_MAX");
return 0;
}
求平均值:
//來源:公衆號【編程珠璣】
#include <stdio.h>
#include <limits.h>
int average(int a,int b)
{
return ( b - (b - a) / 2 );
}
int main()
{
int a = 100;
int b = INT_MAX - 10;
printf("average a b:%d\n",average(a,b));
return 0;
}
但這樣還有問題,爲什麼???
原文地址:https://www.yanbinghu.com/2020/01/01/152.html
來源:公衆號【編程珠璣】
作者:守望先生
ID:shouwangxiansheng
相關精彩推薦
關注公衆號【編程珠璣】,獲取更多Linux/C/C++/數據結構與算法/計算機基礎/工具等原創技術文章。後臺免費獲取經典電子書和視頻資源