【C语言】关于宏定义中#和##符号的使用和宏定义展开问题

【001 关键字】宏定义中的#和##的用法 一、字符串化操作符 # # 的功能:将其后面的宏参数进行字符串化操作。 注意:只能用于有传入参数的宏定义中,且必须置于宏定义体中的参数名前。 #include<stdio.h> #define Str(s) #s int main() { printf(Str(HelloWorld)); return; } 输出:HelloWorld 二、符号连接操作符 ## ##是连接符,前加##或后加##,将标记作为一个合法的标识符的一部分 #include<stdi 阅读详情

1.#在英语里叫做pound,在C语言的宏定义中,一个#表示字符串化,两个#代表concatenate。

</pre><p></p><p>2.<span style="font-family:宋体">实例一:</span></p><p></p><pre name="code" class="cpp">#include <iostream>
void quit_command(){
    printf("I am quit command\n");
}   
void help_command(){
    printf("I am help command\n");
}   
struct command
{
    char * name;
    void (*function) (void);
};  
#define COMMAND(NAME) {#NAME,NAME##_command}
#define PRINT(NAME) printf("token"#NAME"=%d\n", token##NAME)
main(){
    int token9=9;
    PRINT(9);
    struct command commands[] = {
        COMMAND(quit),
        COMMAND(help),
    };  
    commands[0].function();
}

结果是:

 

那么下面的一个经典题目的答案呢?

3.程序如下:

#include <stdio.h>
#define f(a,b) a##b
#define g(a) #a
#define h(a) g(a) 
int main(){  
printf("%s\n", h(f(1,2)));  
printf("%s\n", g(f(1,2)));  
return 0;}


运行结果如下:


为什么是这个结果呢?先看关于宏展开。

4.宏展开

预处理过程的几个步骤:

 

1)字符集转换(如三联字符)

 

2)断行链接/

 

3)注释处理,/* comment */,被替换成空格

 

4)执行预处理命令,如#inlcude、#define、#pragma、#error等

 

5)转义字符替换

 

6)相邻字符串拼接

 

7)将预处理记号替换为词法记号

 

第4步即如何展开宏函数的规则:在展开当前宏函数时,如果形参有#或##则不进行宏参数的展开,否则先展开宏参数,再展开当前宏。

5.总结

综合以上,对于这道题来说,第一行h(f(1,2)),由于h(a)非#或者##所以先展开其参数f(1,2),即12,所以变成h(12),然后再宏替换为g(12),再次替换为12。

第二行g(f(1,2)),宏g(a)带有#,所以里面的f(1,2)不展开,所以变成f(1,2)


小知识:C语言宏定义中 # 和 ## 符号的用法 在某些C语言代码中,有时我们可能会看到宏定义中带有#、##,这些符号有特殊的作用,下面我们用几个简单的例子来说明。 1)一个#的作用 一个#的作用就是把后面的参数当做一个字符串,也就是说等同于把后面的宏变量加上双引号: 运行上述代码,可以得到输出: Hello world 1 Hello world 2 说明 #define PRINT(NAME) printf(#NAME)这个宏,等同于把NAME加上了双引号“”,即替换成了“NAME”,所以,第一个PRINT可以直接把括号内的内容.. 阅读详情

相关推荐

C语言宏定义"#","##"巧妙用法

C语言宏定义的巧妙用法 在我学习32的过程中发现了这样一段代码: /*信息输出*/ #define EEPROM_DEBUG_ON 1 #define EEPROM_INFO(fmt,arg...) printf("<<-EEPROM-INFO->> "fmt"\n",##arg) #define EEPROM_ERROR(fmt,ar...

qq_41950660的博客 2840

带参数的函数,pound()调用注释

#include<stdio.h> void pound(int n);//ANSI函数原类型声明 int main(void) { int a = 5; char ch = '!';//ASCII码33 float f = 7.0; pound (a);//int类型参数 pound (ch);//和pound(int)ch)相同 pound (f);//和pound(int)f)相同 return 0; //把pound三个值赋予给'n,a ,ch

2201_75658688的博客 647

ComfyUI新手必看:JoyCaption 2插件安装全流程(附百度网盘资源)

本文为ComfyUI新手提供了JoyCaption 2插件的完整安装与部署指南。详细介绍了从环境准备、插件获取、模型文件配置到核心节点使用的全流程,并重点解析了其集成的LLM反推模式,帮助用户高效实现从图片到精准提示词的转换。

mango的博客 311

C语言的宏定义、宏展开

①一个较长的宏定义可以分成若干行,这需要在待续的行末尾加上一个反斜杠符”\” #defineTUP_ASSERT(__expression)do {\ if (!( __expression )) \ { \ SYSLOG_LEGACY(EAaSysLogSeverityLevel_Error,"<TUP ASSERTION FAILED> (%s) file: %s line:%u", #__expression,__FILE...

c2737647040的博客 6216

Ubuntu 22.04 局域网安装GitLab

下面直接给你一份。

u013250861的博客 680

Parrot OS最新安装教程

Parrot OS和Kali Linux一样是一个基于 Debian 的免费开源 Linux 发行版,适合安全专家、开发人员、以及关心隐私的人。相较于Kali,Parrot OS属于轻量级,对于硬件的要求无需很高,目前版本已更新到6.3。通过按照本教程的方法,能够成功安装Parrot OS。

🦸💻冰草花生酱提醒您“请记得检查所有电子设备的最后登录时间哦⏰🔍” 4449

C语言宏定义时#(井号)和##(双井号)的用法

http://www.cnblogs.com/welkinwalker/archive/2012/03/30/2424844.html #在英语里面叫做 pound 在C语言的宏定义中,一个#表示字符串化;两个#代表concatenate 举例如下:   #include  void quit_command(){     printf("I am qui

beckdon的专栏 1266

STM32F4使用CUBEMX ADC定时采样+DMA

STM32、FFT、ADC、TIM

m0_62379750的博客 4227

C语言学习(五)运算符、表达式和语句

5.2 基本运算符 基本算术运算的运算符: =、 +、 -、 *和/ C 没有指数运算符。不过, C 的标准数学库提供了一个pow()函数用于指数运算。 例如, pow(3.5, 2.2)返回3.5的2.2次幂) 。 C使用符号/来表示除法。 /左侧的值是被除数, 右侧的值是除数。 例如, 下面four的值是4.0: four = 12.0/3.0; 整数除法和浮点数除法不同。 浮点数...

Whale 2533

FDTD仿真实战:从材料导入到反射率曲线分析

本文提供了一份完整的FDTD仿真实战指南,详细讲解了从自定义材料(如WO3)数据导入、结构建模、仿真区域与网格设置,到光源与监视器配置、运行仿真并提取反射率数据的全流程。重点解决了材料库缺失、网格优化、边界条件设置等常见难题,旨在帮助研究人员高效、准确地通过FDTD仿真获取材料的关键光学特性——反射率曲线。

elastic6hunter的博客 349

RK3588部署YOLOv11与RKNN全流程教程

本文详细介绍了在RK3588开发板上部署YOLOv11目标检测模型的全流程。主要内容包括:PC端CUDA/cuDNN环境配置、Anaconda虚拟环境搭建、RKNN Toolkit2安装;YOLOv11模型从PyTorch到ONNX再到RKNN的格式转换;以及RK3588开发板的系统配置、RKNPU驱动安装和最终推理实现。教程提供了完整的代码示例,帮助开发者快速在边缘设备上实现高效的AI推理应用,涵盖从环境准备到实时检测的全套解决方案。

FJN110的博客 381

python展开 c函数中的宏预处理_【C语言】关于宏定义中#和##符号的使用和宏定义展开问题...

有一道经典的C语言问题,关于宏定义中#和##符号的使用和宏定义展开问题程序如下:#include #define f(a,b) a##b#define g(a) #a#define h(a) g(a)int main(){printf("%s\n", h(f(1,2)));printf("%s\n", g(f(1,2)));return 0;}答案:第一行:12 第二行:f(1,2)说明:1...

weixin_39909366的博客 278

OpenHarmony可信执行环境:TEE模块源码分析与实现原理

TEE(Trusted Execution Environment)是OpenHarmony系统中的安全执行环境,用于提供隔离的安全执行环境,保护敏感数据和操作。OpenHarmony的TEE模块基于OpenTrustee实现,采用微内核架构,为系统提供可信执行环境支持。OpenHarmony TEE模块是一个复杂的安全系统,通过提供隔离的执行环境保护敏感数据和操作。

m0_67505153的博客 558

关于C语言宏定义#define的心得

最近在搞单片机,发现#define的用法实在太令我吃惊了,功能强大,且非常有趣,特别是关于\、#、@的用法,在博客园其他地方找到一篇文章如下: 地址:http://www.cnblogs.com/wangkangluo1/archive/2011/07/11/2103258.html define是C语言中的预处理命令,它用于宏定义,可以提高源代码的可读性,为编程提供方便。预处理命令以“#”号...

weixin_34387284的博客 99

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

C语言宏定义技巧(常用宏定义)

写好C语言,漂亮的宏定义很重要,使用宏定义可以防止出错,提高可移植性,可读性,方便性 等等。下面列举一些***软件中常用得宏定义: 1,防止一个头文件被重复包含 #ifndef COMDEF_H #define COMDEF_H   //头文件内容 #endif 2,重新定义一些类型,防止由于各种平台和编译器的不同,而产生的类

ljzcom的专栏 766

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

C语言中几个容易踩的“坑”!

今天给大家分享几个C语言中的坑。一、带参数的宏展开顺序#include #definef(a,b)a##b #defineg(a)#a #defineh(a)g(a) in...

轻松学C语言 315

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

define宏定义中的#,##,@#及/符号

前言 本文描述define宏定义中的#,##,@#及/符号的使用方法 #的用法 宏定义中的#字符串化操作符。其作用是:将宏定义中的传入参数名转换成用一对双引号括起来参数名字符串。其只能用于有传入参数的宏定义中,且必须置于宏定义体中的参数名前。 例子 #define STR(str) #str STR(123)会被扩展为123 int a = 123; STR(a); // 这里的宏会扩展为"a" 这里的宏会扩展为"a" 注意 对空格的处理 忽略传入参数名前面和后面的空格。 如:STR( abc

qq_36963214的博客 4203

C语言宏定义中,“#”符和“##”符的作用含义

寞水

寞水 1万+

C语言宏定义##连接符和#符的使用

## 连接符号由两个井号组成,其功能是在带参数的宏定义中将两个子串(token)联接起来,从而形成一个新的子串。但它不可以是第一个或者最后一个子串。所谓的子串(token)就是指编译器能够识别的最小语法单元。 简单的说,“##”是一种分隔连接方式,它的作用是先分隔,然后进行强制连接。其中,分隔的作用类似于空格。我们知道在普通的宏定义中,预处理器一般把空格解释成分段标志,对于每一段...

EE漫谈 9701

C语言中“#“和“##“的用法

C语言中"#"和"##"的用法 1. 前言 使用#把宏参数变为一个字符串,用##把两个宏参数贴合在一起. 2. 一般用法 #include<cstdio> #include<climits> using namespace std; #define STR(s) #s #define CONS(a,b) int(a##e##b) int main() { printf(STR(vck)); // 输出字符串"vck" printf(

君君的博客 1万+
上一篇: C/C++静态变量static详解
下一篇: C/C++值传递、指针传递和引用传递详解
仲轲
博客等级 码龄13年 73粉丝 28原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值