2
#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'

2
  • I've reformatted and tagged as C since you're using <stdio.h>. Do retag if it's C++. Commented Nov 30, 2016 at 15:34
  • " redefinition of 'i'" Well... look at the code. Why do you think it doesn't work? Commented Nov 30, 2016 at 16:28

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Output is i + j is 465 i + j is 465
That's because you don't re-evalute result after changing i and j. I've amended the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.