C++变量值不变

cod*_*ude 0 c++ variables

我正在使用以下代码(它已被超级简化以找到问题的根源).

#include <iostream>
namespace std;

int user;
int submit(int);

int main() {

    user = 1;
    submit(user);

    user = 2;
    submit(user);

    return(0);
}

int submit(int user) {

    if (user = 1) {
        printf("1");
    } else if (user = 2) {
        printf("2");
    }
    return(0);

}
Run Code Online (Sandbox Code Playgroud)

我认为这会打印出"12",但我会得到"11".在第二次调用函数之前,变量"user"是不是被重新定义了?

这里出了什么问题?

Kei*_*all 8

使用==,而不是=检查的值user.您正在覆盖值(使用=)而不是比较它们(使用==).


ash*_*shr 6

=不在==函数体中使用.

if (user = 1) { //This assigns user the value of 1 and then prints 1
         printf("1");
Run Code Online (Sandbox Code Playgroud)

正确的测试条件应该是:

if (user == 1) { //This checks the value of user and then prints if the condition is true
         printf("1");
Run Code Online (Sandbox Code Playgroud)

在编译时,如果使用gcc,添加选项-Wall在这种情况下很有用,因为它会在测试条件中向您发出有关分配的警告.