Fortran does not give an error when assigning an array

I have a test code here that does not work, as I suspect. I am using the gfortran compiler.

program test implicit none integer, allocatable, dimension(:) :: a integer, allocatable, dimension(:) :: b allocate(a(2)) allocate(b(4)) a = 1 b = 2 write(*,*) a write(*,*) ' ' write(*,*) b write(*,*) ' ' write(*,*) 'a size before', size(a) a = b a = 1 write(*,*) a write(*,*) ' ' write(*,*) b write(*,*) ' ' write(*,*) 'a size after', size(a) end program test 

And I get the following output.

eleven

2 2 2 2

size up to 2

1 1 1 1

2 2 2 2

size after 4

Why am I not getting an error when assigning arrays of different dimensions? Why resized?

+5
source share
1 answer

This is a function called distribution at assignment . When assigning an array to the allocated array, this automatically changes. Therefore, after a = b it is expected that a will have size b .

You can tell the compiler about this warning using the -Wrealloc-lhs .

See also this person post:

-frealloc-LHS

The allocated left part of the internal assignment is automatically (re) if it is either unallocated or has a different shape. The option is enabled by default, unless -std=f95 . See Also -Wrealloc-lhs .

Also see the Doctor's related blog entry , it hurts me when I do this Steve Lionel.

+5
source

Source: https://habr.com/ru/post/1232162/


All Articles