C宏定义中的逗号(,) [英] comma (,) in C Macro Definition

查看:1257
本文介绍了C宏定义中的逗号(,)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未见过这种语法.

I've never seen this syntax before.

#define SNS(s) (s),(sizeof(s)-1)

我正在阅读的方式是SNS(s) = sizeof(s)-1.逗号在做什么?有必要吗?

The way i'm reading this is that SNS(s) = sizeof(s)-1. What is the comma doing? Is it necessary?

int     ft_display_fatal(const char *err, unsigned len, int fd, int rcode)
{ 
    UNUSED(write(fd, err, len));
    return (rcode);
}

主要

return (ft_display_fatal(SNS("File name missing.\n"), 2, 1));

推荐答案

宏只是文本替换,因此它们可以扩展到几乎您想要的任何内容.在这种情况下,宏用于扩展为函数的两个参数.该函数需要一个字符串和字符串中的字符数作为参数,然后SNS()宏会生成它们.所以

Macros are just text replacement, so they can expand to just about anything you want. In this case, the macro is being used to expand into two arguments to a function. The function expects a string and the number of characters in the string as arguments, and the SNS() macro generates them. So

ft_display_fatal(SNS("File name missing.\n"), 2, 1)

扩展为

ft_display_fatal(("File name missing.\n"),(sizeof("File name missing.\n")-1), 2, 1)

这基本上仅在参数为字符串文字时才有用:sizeof("string")char数组的大小,包括尾随的空字节,并且-1减去该字节以获取有效字符数.细绳.这是ft_display_fatal函数的len参数(我不确定为什么不能仅仅使用strlen()本身来获取它-我想这是性能优化).

This is basically only useful when the parameter is a string literal: sizeof("string") is the size of the char array including the trailing null byte, and -1 subtracts that byte to get the number of significant characters in the string. This is the len argument to the ft_display_fatal function (I'm not sure why it can't just use strlen() to get this by itself -- I guess it's a performance optimization).

这篇关于C宏定义中的逗号(,)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆