Reputation: 51
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure factorial_ada is
n, i : Integer;
output : Integer := 1;
begin
Put_Line("Enter the number to be taken factorial of: ");
Get(n);
-- Begin Loop
for i in 2..n
loop
output := output * i;
end loop;
Put("Factorial of ");
Put(n);
Put(" is ");
Put(output);
end factorial_ada;
My code compiles and works but I"m getting a warning which says "variable "i" is never read and never assigned" "for loop implicitly declares loop variable" "declaration hides "i" declared at line 15"
How do I fix this?
Upvotes: 2
Views: 334
Reputation: 25491
If I compile your code with -gnatl
(listing of source with error messages in line), it gives
1. with Ada.Text_IO, Ada.Integer_Text_IO;
2. use Ada.Text_IO, Ada.Integer_Text_IO;
3.
4. procedure factorial_ada is
5.
6. n, i : Integer;
|
>>> warning: variable "i" is never read and never assigned
7. output : Integer := 1;
8.
9. begin
10. Put_Line("Enter the number to be taken factorial of: ");
11. Get(n);
12.
13. -- Begin Loop
14. for i in 2..n
|
>>> warning: for loop implicitly declares loop variable
>>> warning: declaration hides "i" declared at line 6
15. loop
16. output := output * i;
17. end loop;
18.
19. Put("Factorial of ");
20. Put(n);
21. Put(" is ");
22. Put(output);
23.
24. end factorial_ada;
The warnings at line 14 remind you that (ARM 5.5(11))
An object_declaration should not be given for a loop parameter, since the loop parameter is automatically declared by the loop_parameter_specification. The scope of a loop parameter extends from the loop_parameter_specification to the end of the loop_statement, and the visibility rules are such that a loop parameter is only visible within the sequence_of_statements of the loop.
The warning at line 6 is telling you that this i
(an "object declaration", in ARM-speak) has nothing to do with the i
at line 14.
This is similar to the C++ rules: writing
#include <stdio.h>
int main() {
int i;
int output = 1;
int n = 12;
for (int i = 2; i <= n; i++) {
output *= i;
}
printf("factorial %d is %d\n", i, output);
return 0;
}
results in
$ g++ hk.cc -Wall
hk.cc: In function 'int main()':
hk.cc:9:9: warning: 'i' is used uninitialized in this function [-Wuninitialized]
9 | printf("factorial %d is %d\n", i, output);
| ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Upvotes: 6