comma (,) in C Macro Definition

巧了我就是萌 提交于 2020-01-13 13:13:06

问题


I've never seen this syntax before.

#define SNS(s) (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);
}

Main

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

回答1:


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)

expands into

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

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).




回答2:


The way i'm reading this is that SNS(s) = sizeof(s)-1.

You are reading it wrong.

What is the comma doing?

Macro expansion results in textual substitution. You can use SNS(a) to pass two arguments to a function.

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

You can see that ft_display_fatal takes 4 arguments, but only 3 are provided. This works because SNS expands to 2 arguments. If it didn't, you'd get a compiler error.



来源:https://stackoverflow.com/questions/50635796/comma-in-c-macro-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!