在 C 中,使用未初始化的变量是未定义的行为。包括:
int x;
int y = x;
但是,假设我有以下内容:
struct Struct {
int a;
int b;
};
struct Struct s;
s.a = 1;
struct Struct s0 = s;
return s; // Assuming an enclosing function with the correct return type
在已分配部分(但不是全部)元素的情况下,上述代码是否会调用未定义的行为?
只要您不尝试访问统一的结构成员,就不存在未定义的行为。一旦您开始使用该未初始化的值,那么您就进入了 UB 领域。