Complex constants and variables

I always specify the second value, perhaps a quirk but I prefer to. I (think) I know the rules now, but I do remember some struggles with complex values. Hard to remember them all now but for a tweet there might be some fodder here:

program testit
integer,parameter :: dp=kind(0.0d0)
complex :: c1
real(kind=dp) :: d1=100.0d0, d2=200.0d0
complex(kind=dp) :: c2(3)

write(*,*)cmplx(10) ! one value is allowed

write(*,*)cmplx(20.0d0,20.0d0) ! this is default kind
write(*,*)cmplx(20.0d0,20.0d0,kind=dp) ! this gets doubleprecision
! this gets doubleprecision using %kind if compiler has this yet
write(*,*)cmplx(d1,d2,d1%kind) 

c1=(30,40)  ! allowed with constants
write(*,*)c1
!c2=(d1,d2) ! but cannot do this
c1=(20+3) ! but you can do this because it is an expression 
          ! and () is actually not defining a complex value. It is the same as "c1=20+3"
write(*,*)c1,(20+3)

c1%re=d1; c1%im=d2
write(*,'(g0,"+i",g0)')c1 ! you have to define two fields for complex
write(*,*) c1  ! note the parenthesis
write(*,'(g0)') ! g0 and * produce very different results with complex, unlike with most other values

end program testit

Your descriptions are great, by the way. WIsh some textbooks were as clear.

1 Like