5

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));
dbc
  • 104,963
  • 20
  • 228
  • 340
Gabe Spound
  • 568
  • 5
  • 28

2 Answers2

7

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1) Oops. sorry for that, that is why I rolled back. 2) An uncommon reason for `sizeof(s)-1` vs. `strlen()` is to determine the the "length" of the _string literal_ even if it contained embedded _null character_ - a rare situation. – chux - Reinstate Monica Jun 01 '18 at 03:58
  • I thought **I** rolled it back. Anyway, while that's a possible use, it's very clearly not the intent in this case. The macro is designed specifically to work with that function, which is used to write text. – Barmar Jun 01 '18 at 04:00
  • Yes the "performance optimization" is a more likely scenario. Given that it is a _fatal message_, minimal processing is a wise choice. – chux - Reinstate Monica Jun 01 '18 at 04:03
4

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.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362