If I declare a variable and do not use it in the body of the program, will it compile?

Asked

Viewed 99 times

-2

I have a program and left a declared variable, but I did not use in the body of the program.

  • 1

    Have you tried compiling this program? Maybe it already answers your own question :)

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

3 answers

3

Depends on the compiler configuration. You can enable or disable this. There’s a very simple way to find out what your compiler default is, Compile under these conditions and see if it compiles. I advise to keep this on and not leave a declared variable and no use, you forget it there and will disorganize the code, if not used, delete it, if you need more forward create again.

Note that the variable will not be created in the application. At least in C variables are only created if they have use, the question is only organization of the code. In fact even used variables can be removed after compiled, variable is a concept only exists in code. Whether or not it will take up space in memory is a secondary issue. In many cases even used variables disappear totally and everything ends up being done in the register, not consuming memory.

For those who have never seen it not compile for that reason it is only see in the ideone a simple code that does not compile.

1

I have never seen a situation where the program does not Compile for this reason, but this is not enough to say that it will always work.

If Compile and the compiler use an optimization technique called DCE (Dead Code Elimination), variable will not be part of the final build result. More details, for example: http://compileroptimizations.com/category/dead_code_elimination.htm

  • 2

    It is possible to compile and have all warnings interpreted as errors, in which case it would not actually compile. But this will not be the default of course, it is necessary that the person has configured this way previously.

0

In case you want to keep only to remember you can mark as momentary, so there is no risk to be occupying unnecessary memory, although as already mentioned by colleagues above, depending on the configuration the compiler will remove.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.