Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use macros in printf function

Tags:

c

macros

So I have this macro and a bunch others defined in my header file

#define COL1WIDTH 16

Which I want to use to print something like this:

word  25 Dir1/FileB 129 Sat Jan 1 00:00:02 2011 12 1(x4), 2(x2), 3(x2), 4(x2), 5(x2) 

How does the syntax to get the macro work? Tried a bunch and it keeps screwing up.

Tried this

printf("%COL1WIDTHs\t",index->terms[0].term);
like image 201
Terrence 'MrBlue' Wong Avatar asked Nov 18 '25 03:11

Terrence 'MrBlue' Wong


2 Answers

printf("%" #COL1WIDTH "s\t", ...

Read up on token pasting and stringizing in the C pre-processor.

like image 96
David Schwartz Avatar answered Nov 20 '25 16:11

David Schwartz


Macros aren't expanded inside strings. Here there's a decent workaround — write

printf("%*s\t", COL1WIDTH, index -> terms[0].term);

and COL1WIDTH will be used in place of the *.

like image 44
Joshua Green Avatar answered Nov 20 '25 17:11

Joshua Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!