Tuhin Bhatt
Tuhin Bhatt

Reputation: 362

Unused Variable Error in C .. Simple Question

I get error in C(Error- Unused Variable) for variable when I type in following code

int i=10;

but when I do this(break it up into two statements)

int i;
i=10;

The error Goes away

..I am using Xcode(ver-4.1)(Macosx-Lion).. Is something wrong with xcode....

Upvotes: 2

Views: 21036

Answers (3)

Gekwonder
Gekwonder

Reputation: 1

(void) i;

You can cast the unused variable to void to suppress the error.

Upvotes: -1

Keith Thompson
Keith Thompson

Reputation: 263267

The compiler isn't wrong, but it is missing an opportunity to print a meaningful error.

Apparently it warns if you declare a variable but never "use" it -- and assigning a vale to it qualifies as using it. The two code snippets are equivalent; the first just happens to make it a bit easier for the compiler to detect the problem.

It could issue a warning for a variable whose value is never read. And I wouldn't be surprised if it did so at a higher optimization level. (The analysis necessary for optimization is also useful for discovering this kind of problem.)

It's simply not possible for a compiler to detect all possible problems of this kind; doing so would be equivalent to solving the Halting Problem. (I think.) Which is why language standards typically don't require warnings like this, and different compilers expend different levels of effort detecting such problems.

(Actually, a compiler probably could detect all unused variable problems, but at the expense of some false positives, i.e., issuing warnings for cases where there isn't really a problem.)

UPDATE, 11 years later:

Using gcc 11.3.0 with -Wall, I get warnings on both:

$ cat a.c
int main() {
    int i = 10;
}
$ gcc -Wall -c a.c
a.c: In function ‘main’:
a.c:2:9: warning: unused variable ‘i’ [-Wunused-variable]
    2 |     int i = 10;
      |         ^
$ cat b.c
int main() {
    int i;
    i = 10;
}
$ gcc -Wall -c b.c
b.c: In function ‘main’:
b.c:2:9: warning: variable ‘i’ set but not used [-Wunused-but-set-variable]
    2 |     int i;
      |         ^
$ 

But clang 8.0.1 does not warn on the second program. (XCode probably uses clang.)

The language does not require a warning, but it would certainly make sense to issue one in this case. Tests on godbolt.org indicate that clang issues a warning for the second program starting with version 13.0.0.

Upvotes: 3

Alok Save
Alok Save

Reputation: 206526

No nothing is wrong the compiler just warns you that you declared a variable and you are not using it.
It is just a warning not an error.
While nothing is wrong, You must avoid declaring variables that you do not need because they just occupy memory and add to the overhead when they are not needed in the first place.

Upvotes: 6

Related Questions