2

I have the same question as this one, except I'm writing C.

How can I initialize a literal number to have the type size_t?

Basically, I have a macro that amounts to this:

#define myprint(S) { printf("hello %zu", S); }

and I would like to use it like this:

myprint(0);

But I'm getting the message:

format '%zu' expects argument of type 'size_t', but argument has type 'int'

I've tried writing 0lu, but it does not work for all architectures.

Lars Nyström
  • 5,786
  • 3
  • 32
  • 33
  • 4
    There is no literal suffix for this. Use a cast: `(size_t) foo`. – Eric Postpischil Jun 24 '20 at 14:23
  • @EricPostpischil That's what I feared. Perhaps you could add your comment as an answer? – Lars Nyström Jun 24 '20 at 14:26
  • You should also put parentheses around that macro parameter in the expansion. – Ian Abbott Jun 24 '20 at 14:38
  • Safer version: `#define myprint(S) ( (void)_Generic((S), int: 0, size_t: 0), printf("hello %zu", (size_t)(S)) ) ` – Lundin Jun 24 '20 at 14:48
  • safest version `void myprit(const size_t size) { ... }` – 0___________ Jun 24 '20 at 15:30
  • @P__J__: Making it external rather than static inline, and gratuitous qualifier on arg, aren't the best ideas, but indeed using a function (ideally static inline) rather than a macro for this is the right thing to do. – R.. GitHub STOP HELPING ICE Jun 24 '20 at 17:53
  • @R..GitHubSTOPHELPINGICE why it is not the best idea? Because you think so? But you are wrong. Inlining or not inlining, static or not static depends on the use. Why const: – 0___________ Jun 24 '20 at 18:06
  • @P__J__: Because (1) static inline is closer to OP's original intent with the macro; an external function has different linking semantics, and (2) the body is inherently so small (just wrapping another function call) that inline will not be any larger. – R.. GitHub STOP HELPING ICE Jun 24 '20 at 20:26
  • @R..GitHubSTOPHELPINGICE leave for the compiler. BTW inline function does not have to be inlined unless you force the the compiler to do so. You did not answer why it is bad to be const correct. – 0___________ Jun 24 '20 at 20:28

1 Answers1

4

There's no suffix specific to size_t. You'll need to use a cast instead.

#define myprint(S) { printf("hello %zu", (size_t)S); }

Given how this is used, it's the best way to do it anyway.

dbush
  • 205,898
  • 23
  • 218
  • 273