1

I can't seem to figure out what I'm doing wrong here. I'm getting the following error for the code below. Any ideas?

enter image description here

enter image description here

1 Answer 1

5

With your usage of int you're creating a new variable. Example:

int blocks = 5; 

{// Just creating a block, similar to a loop
  int blocks = 4; //Variable inside the block
  printf("%d\n", blocks); // Prints 4
}

printf("%d\n", blocks); //Variable outside block / prints 5

The int blocks = 4 variable lives only inside of the block {}, it's inside the block's scope and can only be accessed within the block scope.

You can achieve the result you want by simply not using the int keyword in your do..while loop, that means you're not creating a new variable and you can access blocks outside of the loop. Example:

int blocks = 5;

{
  blocks = 100; //Same variable as int blocks = 5
  printf("%d\n", blocks); //prints 100
}

printf("%d\n", blocks); //The variable we started with is now changed as well, will print 100

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .