How to printf “unsigned long” in C?
%lu is the correct format for unsigned long. Sounds like there are other issues at play here, such as memory corruption or an uninitialized variable. Perhaps show us a larger picture?
%lu is the correct format for unsigned long. Sounds like there are other issues at play here, such as memory corruption or an uninitialized variable. Perhaps show us a larger picture?
Yes: use the z length modifier: size_t size = sizeof(char); printf(“the size is %zu\n”, size); // decimal size_t (“u” for unsigned) printf(“the size is %zx\n”, size); // hex size_t The other length modifiers that are available are hh (for char), h (for short), l (for long), ll (for long long), j (for intmax_t), t (for … Read more
One possible reason: for symmetry with the use of those modifiers in the formatted input functions? I know it wouldn’t be strictly necessary, but maybe there was value seen for that? Although they don’t mention the importance of symmetry for the “h” and “hh” modifiers in the C99 Rationale document, the committee does mention it … Read more
Your array needs to be able to hold four chars, since it must also contain the 0-terminator. With that fixed, specifying a maximal length in the format, scanf(“%3s”, string); ensures that scanf reads no more than 3 characters.
You can use an asterisk (*) to pass the width specifier/precision to printf(), rather than hard coding it into the format string, i.e. void f(const char *str, int str_len) { printf(“%.*s\n”, str_len, str); }
You can use z for size_t and t for ptrdiff_t like in printf(“%zu %td”, size, ptrdiff); But my manpage says some older library used a different character than z and discourages use of it. Nevertheless, it’s standardized (by the C99 standard). For those intmax_t and int8_t of stdint.h and so on, there are macros you … Read more
They are the same when used for output, e.g. with printf. However, these are different when used as input specifier e.g. with scanf, where %d scans an integer as a signed decimal number, but %i defaults to decimal but also allows hexadecimal (if preceded by 0x) and octal (if preceded by 0). So 033 would … Read more
Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU). printf(“%llu”, 285212672);
what happens when I use the wrong format specifier in C? Generally speaking, undefined behaviour.* However, recall that printf is a variadic function, and that the arguments to variadic functions undergo the default argument promotions. So for instance, a char is promoted to an int. So in practice, these will both give the same results: … Read more
“%f” is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it’ll be promoted to double before printf receives it1. “%lf” is also acceptable under the current standard — the l is specified as having no effect … Read more