So does the compiler neglect completely the unused variable
Depends what you mean by "neglect". The compiler optimizes the code, but doesn't completely ignore the variable, as otherwise compiler couldn't calculate the result.
not output it in the executable?
Yes.
If so why is the output of program correct?
Because this is what a compiler does - generates programs with the output as described by the programming language. Code is not 1:1 to assembly, code is a language that describes the behavior of a program. Theoretically, as long as the output of the compiled program is correct with what is in the source code, compiler can generate any assembly instructions it wants.
You may want to research the terms side effect and the as-if rule in the context of C programming language.
Can anyone explain the working of unused and used variable attributes in gcc.
There is no better explanation then in GCC documentation about Variable Attributes:
unused
This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC does not produce a warning for this variable.
used
This attribute, attached to a variable with static storage, means that the variable must be emitted even if it appears that the variable is not referenced.
When applied to a static data member of a C++ class template, the attribute also means that the member is instantiated if the class itself is instantiated.
The attribute unused
is to silence the compiler warning from -Wunused-*
warnings.
The attribute used
is meant to be used on variables (but I think works also on functions) so that the variable is generated to the assembly code. even if it is not unused anywhere.