How to write perfect C code

简介:

 Several days ago, I was involved in an argument about choice of C or C++. What I ignored was "language is less important than coder".  a bad C# writer only write shit-like C# but a professional C programmer could design perfect C, Notwithstanding C# is much more powerful than C,
So how to write perfect C code? We just illustrate that by cJson, a famous pure-C tiny json formatter. 

   1. Power C pointer, make point operation awesome      

    The string-comparison of cjson like melody,  this ability might need you a lot experience:

复制代码
    static int cJSON_strcasecmp(const char *s1,const char *s2)
    {
    if (!s1) return (s1==s2)?0:1;
    if (!s2) return 1; for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0; return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); } 
复制代码

  So how you write a same strcasecmp function? Try more C code.

    2. Reasonable code indent        

   Someone might tell you write code with same indent-style, "the wrap position, where to put a bracket..." However, most people are accustomed to reading left to right without pause. So a better code reader understand is more important than that so-call rule and style just like follows:

复制代码
static const char *parse_value(cJSON *item,const char *value)
{
    if (!value)                        return 0;    /* Fail on null. */
    if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } if (*value=='\"') { return parse_string(item,value); } if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); } if (*value=='[') { return parse_array(item,value); } if (*value=='{') { return parse_object(item,value); } ep=value;return 0; /* failure. */ }
复制代码

 

  Does Code below make it more easy to understand than standard indent style? As you can easily compare difference between each case of switch structure.        

    3. Chain-style function design    

  Chain-style function means you can invoke them with merge them into a chain, as A(B(C)).
Linq (a chain-style code sugar ) greatly improve beauty of C#, could make your code designed like: Select.Where.Orderby...  As standard C do not offer extend-function. But you could still make the chain like Order(Select(Where(Data))) .  Some little bit harder ,but much more easier than other code style, just like code in cJson:
    

   value=skip(parse_value(child,skip(value+1)));    /* skip any spacing, get the value. *


    The difficulty is the rope which connect modules into a chain. In Linq, it's a interface called IEnumerable, a compiler-level state machine. In cJson code behind, it's the position of processing pointer. 

       4. Hook me!    

   Standard C do not have delegate, function override. But there are some other powerful mechanism called hook, achieved by function pointer. You could change a function pointer behaviour by assign a different function with same parameters and return value. Example as follow:

复制代码
    void cJSON_InitHooks(cJSON_Hooks* hooks)
{
    if (!hooks) { /* Reset hooks */
        cJSON_malloc = malloc;
        cJSON_free = free;
        return; } cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; cJSON_free = (hooks->free_fn)?hooks->free_fn:free; }
复制代码

 

    Awesome right? You can change memory allocation and free behaviour by using hook!

    5. Offer default value of function parameters    

   In order to make your user more convenient when using your perfect library, please offer them some override functions! C might not allow you define two same name function by different parameter table. But you could still do this:

/* Render a cJSON item/entity/structure to text. */
char *cJSON_Print(cJSON *item)                {return print_value(item,0,1);}
char *cJSON_PrintUnformatted(cJSON *item)    {return print_value(item,0,0);}

 6.  Marco and #define  

   Marco is only way to make C transplant in different platform.

6. Improve algorithm!    

   C style code is different than C# or Java, the languages with powerful libraries. Sometimes because of compatibility or performance, using STL or some 3rd libraries is not a good choice. So you need to achieved them by yourself. This does not means you should write "Stack.c" or  "Stack.h"  to define a full-functional stack. It's too heavy and unnecessary,right? But the core algorithm of stack will greatly affect your code style by merge an easy array-achieved stack by several simple code.
    The example in cJson is tree structure, as json is a nature tree. The author merge tree algorithm into the code by recursive and pointer without any trace. Perfect!
    
    Try more C code, try more perfect improvement, guy!


作者:热情的沙漠
出处:http://www.cnblogs.com/buptzym/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。


 本文转自FerventDesert博客园博客,原文链接:http://www.cnblogs.com/buptzym/p/4318502.html,如需转载请自行联系原作者

目录
相关文章
|
机器学习/深度学习 调度
详解 Diffusion (扩散) 模型
详解 Diffusion (扩散) 模型
|
人工智能 文字识别 监控
将人工智能融入多媒体 助力视频产业加速——阿里云视频AI全能力解读
结合人工智能视频理解流程和用户的需求场景,我们将视频AI的功能分成四个大部分,视频智能审核、视频内容理解、视频智能编辑、视频版权保护。其中视频审核功能包括视频鉴黄、暴恐涉政识别、广告二维码识别、无意义直播识别等,利用识别能力将网络上没营养和不健康的视频内容进行排查和处理;视频理解功能包括视频分类、标签,人物识别、语音识别,同时也包括对视频中的文字进行识别(OCR);视频编辑层面可以实现视频首图、视频摘要、视频highlight的生成,同时支持新闻拆条;关于视频版权,支持视频相似性、同源视频检索和音视频指纹等功能。
17679 0
将人工智能融入多媒体 助力视频产业加速——阿里云视频AI全能力解读
|
机器学习/深度学习 算法 openCL
高效、轻量的深度学习框架MNN
MNN是一个高效、轻量的深度学习框架。
高效、轻量的深度学习框架MNN
|
9月前
|
Linux Docker 容器
Linux 中停止 Docker 服务报 warning 导致无法彻底停止问题如何解决?
在 Linux 系统中,停止 Docker 服务时遇到警告无法彻底停止的问题,可以通过系统管理工具停止服务、强制终止相关进程、检查系统资源和依赖关系、以及重置 Docker 环境来解决。通过以上步骤,能够有效地排查和解决 Docker 服务停止不彻底的问题,确保系统的稳定运行。
618 19
|
缓存 网络协议 安全
【计算巢】DNS 解析过程详解:域名如何转换为 IP 地址
【5月更文挑战第31天】DNS(域名系统)将人类可读的域名转换为IP地址,涉及本地DNS缓存、层次化DNS服务器系统,包括根DNS、顶级域名DNS和权威DNS。当查询域名时,通过DNS服务器间的交互找到对应IP并返回给浏览器。Python示例展示了DNS查询过程。尽管DNS面临安全挑战,如欺骗和缓存中毒,采取安全措施可确保其稳定性和安全性。它是互联网的重要基础,连接域名与IP,支持便捷的网络访问。
537 0
|
人工智能 缓存 安全
阿里云服务器实例规格性能参考:从五代到八代及经济型e与通用算力型u1
阿里云不断推出新一代的云服务器实例规格,以满足不同用户的多样化需求。本文将介绍阿里云服务器从五代到八代的实例规格,以及经济型e和通用算力型u1这两种热门实例规格,帮助用户更好地选择适合自己的云服务器。
阿里云服务器实例规格性能参考:从五代到八代及经济型e与通用算力型u1
|
11月前
|
数据可视化 搜索推荐 数据挖掘
2024年备受推荐的数据可视化平台——团队管理必备利器
在数字化时代,数据已成为决策、管理和运营的核心。数据可视化平台通过直观的图表形式,帮助企业和团队高效解读和分析数据,提升项目管理、团队绩效评估、资源分配、销售与市场分析等方面的能力。2024年推荐的五大数据可视化平台包括板栗看板、Tableau、PowerBI、QlikView和Looker,各具特色,适用于不同场景和需求。板栗看板操作简便,适合团队协作;Tableau功能强大,适合大型企业;PowerBI与微软生态系统无缝集成;QlikView擅长处理海量数据;Looker则专注于数据探索和商业智能。希望本文能帮助用户选择合适的可视化平台。
1917 2
2024年备受推荐的数据可视化平台——团队管理必备利器
|
小程序
【微信小程序】英文字母不换行问题 flex布局字符超出宽度折行问题:设置了word-break: break-all;和flex: 1;冲突flex不生效问题
【微信小程序】英文字母不换行问题 flex布局字符超出宽度折行问题:设置了word-break: break-all;和flex: 1;冲突flex不生效问题
443 1
|
存储 数据处理 C++
内存 vs 硬盘:固态硬盘代替内存可以工作吗?
内存 vs 硬盘:固态硬盘代替内存可以工作吗?
395 2
|
前端开发 搜索推荐 UED
单页面应用(SPA)与多页面应用(MPA)的区别及优缺点
单页面应用(SPA)与多页面应用(MPA)的区别及优缺点
360 1