几个简单但你可能忽略的C知识点

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

相关精彩推荐

每天都在用printf,你知道变长参数是怎么实现的吗

你可能不知道的printf

C语言入坑指南-被遗忘的初始化

C语言入坑指南-整型的隐式转换与溢出

关注公众号【编程珠玑】,获取更多Linux/C/C++/数据结构与算法/计算机基础/工具等原创技术文章。后台免费获取经典电子书和视频资源

发布了153 篇原创文章 · 获赞 1106 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/hyb612/article/details/103829609