http://www.cplusplus.com/reference/cstdio/snprintf/
https://www.unix.com/man-page/All/3c/snprintf/
https://en.cppreference.com/w/c/language/restrict

int snprintf(char *restrict s, size_t n, const char *restrict format, /* args*/ ...);

The snprintf() function is identical to sprintf() with the addition of the argument n, which specifies the size of the buffer referred to by s. If n is 0, nothing is written and s can be a null pointer.

Otherwise, output bytes beyond the n-1st are discarded instead of being written to the array and a null byte is written at the end of the bytes actually written into the array.

pointer aliasing

In computer programming, aliasing refers to the situation where the same memory location can be accessed using different names.

restrict (a keyword in C)

The restrict keyword is a declaration of intent given by the programmer to the compiler. It says that for the lifetime of the pointer, only the pointer itself or a value directly derived from it (such as pointer + 1) will be used to access the object to which it points.

why: 用來跟compiler說,以優化至提升性能
只能用這個被 restrict 關鍵字修飾的指標來存取這個物件(資料).

snprintf for string concatenation

char buf[20] = "";
snprintf(buf, sizeof buf, "%s%s", buf, "foo");

The above code violates the restrict contract on snprintf, which states that no other argument can point to object buf.

Leave a Reply

Close Menu