每当我在书籍,手册页和网站中查看真实代码或示例套接字代码时,我几乎总会看到类似下面的内容:
struct sockaddr_in foo;
memset(&foo, 0, sizeof foo);
/* or bzero(), which POSIX marks as LEGACY, and is not in standard C */
foo.sin_port = htons(42);
Run Code Online (Sandbox Code Playgroud)
代替:
struct sockaddr_in foo = { 0 };
/* if at least one member is initialized, all others are set to
zero (as though they had static storage duration) as per
ISO/IEC 9899:1999 6.7.8 Initialization */
foo.sin_port = htons(42);
Run Code Online (Sandbox Code Playgroud)
要么:
struct sockaddr_in foo = { .sin_port = htons(42) }; /* New in C99 */ …Run Code Online (Sandbox Code Playgroud)