N
Noob
Hello,
I am aware that, on some platforms, the representation of NULL and 0.0
may not be all-bits-zero.
On such platforms, does setting all bits to 0 with memset invoke UB?
#include <stdio.h>
#include <string.h>
struct foo
{
int i; int j; unsigned u; void *p; double d;
};
int main(void)
{
struct foo bar;
memset(&bar, 0, sizeof bar); /* UB? */
printf("%d %d %u %p %f\n", bar.i, bar.j, bar.u, bar.p, bar.d);
return 0;
}
Would u be correctly initialized? (I think so.)
Would i and j? (I think so, but am not sure.)
I now initialize bar differently...
#include <stdio.h>
#include <string.h>
struct foo
{
int i; int j; unsigned u; void *p; double d;
};
int main(void)
{
struct foo bar = { 0 };
printf("%d %d %u %p %f\n", bar.i, bar.j, bar.u, bar.p, bar.d);
return 0;
}
Will i,j,u,p,d all be correctly initialized to 0?
Does this mean that some compilers must generate different code for
"struct foo bar = { 0 }" than they do for "memset(&bar, 0, sizeof bar)" ?
On platforms where the two are equivalent, I imagine the compiler is free
to use whichever way is best. But on platforms where they are not, the
compiler must be careful?
Regards.
I am aware that, on some platforms, the representation of NULL and 0.0
may not be all-bits-zero.
On such platforms, does setting all bits to 0 with memset invoke UB?
#include <stdio.h>
#include <string.h>
struct foo
{
int i; int j; unsigned u; void *p; double d;
};
int main(void)
{
struct foo bar;
memset(&bar, 0, sizeof bar); /* UB? */
printf("%d %d %u %p %f\n", bar.i, bar.j, bar.u, bar.p, bar.d);
return 0;
}
Would u be correctly initialized? (I think so.)
Would i and j? (I think so, but am not sure.)
I now initialize bar differently...
#include <stdio.h>
#include <string.h>
struct foo
{
int i; int j; unsigned u; void *p; double d;
};
int main(void)
{
struct foo bar = { 0 };
printf("%d %d %u %p %f\n", bar.i, bar.j, bar.u, bar.p, bar.d);
return 0;
}
Will i,j,u,p,d all be correctly initialized to 0?
Does this mean that some compilers must generate different code for
"struct foo bar = { 0 }" than they do for "memset(&bar, 0, sizeof bar)" ?
On platforms where the two are equivalent, I imagine the compiler is free
to use whichever way is best. But on platforms where they are not, the
compiler must be careful?
Regards.