Declaration of x = huge(x) valid?

Some compilers allow this at the beginning of a program, some complain that x is undeclared. Which is right?

   use iso_fortran_env, only: real64
   implicit none
   real(real64) :: x = huge(x)

This works:
ian@ian-Latitude-E7440:~$ nano huge.f
ian@ian-Latitude-E7440:~$ gfortran huge.f -ffree-form
ian@ian-Latitude-E7440:~$ ./a.out
   1.7976931348623157E+308
ian@ian-Latitude-E7440:~$ cat huge.f
use iso_fortran_env, only: real64
   implicit none
   real(real64) :: x = huge(x)
   print *,x
   end program
ian@ian-Latitude-E7440:~$ 

Thank you @IanMartinAjzenszmidt. I already knew gfortran was one of the compilers accepting x = huge(x) in a declaration. What I was asking was whether it was right i.e. whether it was standard-conforming, so that I would know which compiler(s) to report a bug in.

huge, for real or integer x, returns the largest value in the model that includes x. it has the type and type 
parameter of x. excerpt from Modern Fortran Explained 2018 Edition Metcalf, Cohen et al..

Interesting dusty corner question. Could not find anything simple and definitive in the standard myself. Of course you can avoid the problem with huge(0.0d0) or huge(0.0_real64), but that does not answer what
this should do. I thought there was a statement saying a
variable could not be used in the RHS side of an assignment in the statement declaring the variable, which would mean it was not allowed; but could not find such a statement.

Screenshot from 2024-04-08 23-57-01|690x388
huge, for real or integer x, returns the largest value in the model that includes x. it has the type and type
parameter of x. excerpt from Modern Fortran Explained 2018 Edition.
l```

I believe the initial example is standards conforming, due to paragraph 2 from section 10.1.12 Constant expression:

If a constant expression includes a specification inquiry that depends on a type parameter or an array bound of an entity specified in the same specification-part, the type parameter or array bound shall be specified in a prior specification of the specification-part. The prior specification may be to the left of the specification inquiry in the same statement, but shall not be within the same entity-decl unless the specification inquiry appears within an initialization.

I.e. the type inquiry function (huge) depends on a type parameter (the kind), but the “prior specification” is “to the left of the specification inquiry”.

1 Like

It seems you found it. My vote is it should be allowed after reading that; it almost begs using the original OP post as an example for that paragraph in the standard.