You probably did declare them but aren't recognizing it. Did you do something like:
int i, j, k;
which declares 3 integers called i
j
and k
?
You always have to declare your variables, so you must have done so somewhere. :)
One thing that may catch you out is "scope" where a variable will no longer exist outside of the scope in which it was declared.
For example:
do
{
int a = GetInt();
}
while (a < 5);
will not compile, because the integer called a
only exists within those curly braces of the do
statement.
Instead:
int a;
do
{
a = GetInt();
}
while (a < 5);
will be fine.
By the same token, using another example:
for (int i = 0, j = 5; i < j; i++)
{
printf("i is now %d and j is %d\n", i,j);
}
printf("j:%d now equals i:%d\n", j,i);
will not work, because i
and j
only exist within the curly braces of that for
loop.
Instead, your compiler will complain like this:
file.c:10:43: error: use of undeclared identifier 'j'
printf("j:%d now equals i:%d\n", j,i);
^
1 error generated.
but if you want to access i
and j
outside that loop, you can do this:
int i,j;
for (i = 0, j = 5; i < j; i++)
{
printf("i is now %d and j is %d\n", i,j);
}
printf("j:%d now equals i:%d\n", j,i);
and your output should be:
i is now 0 and j is 5
i is now 1 and j is 5
i is now 2 and j is 5
i is now 3 and j is 5
i is now 4 and j is 5
j:5 now equals i:5
(more info)
Okay, unused variable... let's go back to my first example, but with one change:
int a = 0; // add this
do
{
int a = GetInt();
}
while (a < 5);
Now, when it compiles, you won't see an undeclared variable a
in that while line. Instead, you'll see:
file.c:9:9: error: unused variable 'a' [-Werror,-Wunused-variable]
int a = GetInt();
^
1 error generated.
And why is that? You have declared two integers, both called a
. One is in the scope of main()
(that first one) and one is only in the scope of the do
statement. But you never actually use that a
in the do
statement, because the a
in the while statement is the one you first declared.
Check out the short on "Scope" that is found in Week 2 of the course.
https://www.youtube.com/watch?v=UC5QAokAupo