为什么要在C语言中使用宏?

编程入门 行业动态 更新时间:2024-10-23 02:04:00
本文介绍了为什么要在C语言中使用宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: C宏有什么用?

Possible Duplicate: What are C macros useful for?

每隔几个月,我都会渴望去学习一些C语言,这是我的大学编程教育从未涵盖过的.今天是宏.我对宏的基本理解是,它们是一个简单的搜索,可以替换并替换在编译之前的代码中.我在理解为什么时会遇到麻烦.我正在看的大多数基本示例都是

Every few months I get an itch to go learn some bit of C that my crap college programming education never covered. Today it's macros. My basic understanding of macros is they're a simple search and replace that happens on your code prior to it being compiled. I'm having trouble understanding why you'd use macros. Most of the basic examples I'm looking at are something like

TEST(a,%d); #define TEST(a,b) printf(" The value of " #a " = " #b " \n", a) //which expands to printf(" The value of a = %d \n",a);

(来自此处的示例)

从我的新手角度来看,定义一个新函数似乎将为您提供相同的结果.我可以看到,在轻松搜索和替换之前的几天里,宏对于快速修改大量源代码有多大用处,但是有些事情告诉我,我缺少更大的要点.

From my newbie point of view, it seems like defining a new function would give you the same results. I can see how historically macros would be useful for modifying a lot of source quickly in the days before easy search and replace, but something tells me I'm missing some bigger point.

那么宏可以为您做些什么有用的事情?

So what kind of useful things can macros do for you?

推荐答案

一个原因是直到C99,内联关键字在C语言中才成为标准.因此,宏允许您内嵌小函数.它们在某些方面也像模板一样工作.您不必在宏定义中指定类型,例如:

One reason is until C99, the inline keyword was not standard in the C language. Thus macros allowed you to inline small functions. They also in some ways work like templates, ie. you don't have to specify types in the macro definition eg:

#define MAX(x,y) ((x) > (y) ? (x) : (y))

此宏符合整数,双精度数,浮点数等.

This macro is complient with integers, doubles, floats etc.

更多推荐

为什么要在C语言中使用宏?

本文发布于:2023-11-07 22:48:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567649.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:要在   语言

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!