Why does the following code loop 5000 times instead of the 5 times I expect?
int height = 5;
for (int height; height > 0; height -= 1){
printf('Something') }
}
Why does the following code loop 5000 times instead of the 5 times I expect?
int height = 5;
for (int height; height > 0; height -= 1){
printf('Something') }
}
but when I run it, it does not iterate through the loop 5 times but rather something like 5000.
That's because height
declared in the for
loop shadows the one declared outside. So you are
effectively using uninitialized height
, which is potentially undefined behaviour.
You can leave out the declaration in order to use the previously declared value:
int height = 5;
for (; height > 0; height -= 1) {
printf("Something");
}
If you don't want to change height
, you can use a temporary:
int height = 5;
for (int x = height; x > 0; x -= 1) {
printf("Something");
}
which would leave height
unchanged.
Also note that values in single quotes are multi-byte chars and are not strings. So you can't pass 'Something'
to printf
.
Why do you have to redefine variables in a for loop in C
That may be because of the fact that you want to preserve/use the value of variable after the loop.
In case of
int height = 5;
for (int h = height; h > 0; h--){
printf('Something') }
}
height
will have value 5
. While in case of
int height = 5;
for (height; height > 0; height--){
printf('Something') }
}
height
will have value zero after the for
loop.
This is not what redefining originally was.
Basically, because C have scopes, redefining a variable hides all variables from outer scopes:
for (int i=0; i<10; i++)
for (int i=0; i<10; i++) {
// Code that'll be looped 100 times
// Code here can't access the outer `i`
}
If you don't redefine it
for (int i=0; i<10; i++){
for (; i<10; i++)
// Code that'll be looped 10 times
// Code that'll be run only once
}
If you define a variable without initializing it:
for (int h; h>0; h--)
// Code that'll be looped for unknown times
In this code, the initial value of h
is indeterminate. It could be 5000 or zero, or even more than 2,000,000,000! Always assign a value to a variable before using it.
You have to redefine height
variable with user input in your loop definition.
You can do it like this:
int user_input;
scanf("%d", &user_input);
for (int height = user_input; height > 0; height -= 1){
printf("height = %d\n", height);
}
If user enters "5", this code will print this:
height = 5
height = 4
height = 3
height = 2
height = 1