Search code examples
cvariablesredefinitionredefine

How can I redefine variables in C?


#include <stdio.h>
int main(void)
{
    int i = 365, j = 100, result = i + j;

    printf("i + j is %i\n", result);

    int i = 100, j = 1;
    printf("i + j is %i\n", result);

    return 0;
}

9.c:10:10: error: declaration shadows a local variable [-Werror,-Wshadow] 9.c:8:9: error: redefinition of 'i'


Solution

  • Replace int i = 100 with i = 100.

    You are not allowed to redeclare a variable in the same scope in C and C++. But you can set i to a different value, which is what my change does.

    Finally, if you want the final output of result to be the sum of the new values of i and j, then you have to recompute. Put result = i + j; just before the printf call.