Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comma (,) in C Macro Definition

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));
like image 921
Gabe Spound Avatar asked Dec 23 '22 06:12

Gabe Spound


2 Answers

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

like image 155
Barmar Avatar answered Dec 31 '22 02:12

Barmar


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.

like image 41
Employed Russian Avatar answered Dec 31 '22 00:12

Employed Russian