C ++中变量的范围和优先级

有人可以向我解释为什么结果是2,x在使用什么,为什么。

auto x = 0;

int f(int i){
    auto x = 1;
    {
        static auto x = 0;
        x += i;
    }
    return x;
}
int main() {
    cout << f(1) + f(2) <<endl;// result 2
    return 0;
}
评论
  • 罗小乖
    罗小乖 回复

    The inner x shadows the outer one, but the mutations only apply to the inner most scope

    int f(int i){
        auto x = 1;              // consider this "x1"
        {
            static auto x = 0;   // this is "x2"
            x += i;              // mutates "x2" but not "x1"
        }
        return x;                // return "x1" which is still 1
    }
    

    因此

    f(1) + f(2)                  // 1 + 1 == 2