Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Which character should be used for ptrdiff_t in printf?

Tags:

c

pointers

printf

Which character should be used for ptrdiff_t in printf?

Does C standard clearly explains how to print ptrdiff_t in printf? I haven't found any one.

int a = 1; int b = 2;  int* pa = &a; int* pb = &b;  ptrdiff_t diff = b - a;  printf("diff = %?", diff); // % what? 
like image 236
Amir Saniyan Avatar asked Oct 31 '11 13:10

Amir Saniyan


People also ask

What does %% mean in printf?

As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.


2 Answers

It's %td. See here.

like image 64
trojanfoe Avatar answered Oct 11 '22 13:10

trojanfoe


C11 draft explains the length modifier for ptrdiff_t in 7.21.6.1 7 "The fprintf function"

t
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer type argument; or that a following n conversion specifier applies to a pointer to a ptrdiff_t argument.

Use "%td" as in the following: Credit: @trojanfoe

ptrdiff_t diff = b - a; printf("diff = %td", diff); 

If the compiler does not support "%td", cast to a signed type - the longer, the better. Then insure the alternative format and argument match.

// Note the cast printf("diff = %lld", (long long) diff); // or printf("diff = %ld", (long) diff); 

Ref format specifiers

like image 41
chux - Reinstate Monica Avatar answered Oct 11 '22 14:10

chux - Reinstate Monica