Index: gcc/testsuite/gfortran.dg/dummy_optional_arg.f90
===================================================================
--- gcc/testsuite/gfortran.dg/dummy_optional_arg.f90	(revision 0)
+++ gcc/testsuite/gfortran.dg/dummy_optional_arg.f90	(revision 0)
@@ -0,0 +1,11 @@
+! { dg-do compile }
+! PR fortran/45495
+!
+! Code originally submitted by Philip Mason <pmason at ricardo dot com>
+!
+function jack(aa)
+   character(len=*), intent(in) :: aa
+   optional                     :: aa
+   character(len=len(aa)+1)     :: jack ! { dg-error "cannot be OPTIONAL" }
+   jack = ''
+end function jack
Index: gcc/fortran/expr.c
===================================================================
--- gcc/fortran/expr.c	(revision 163791)
+++ gcc/fortran/expr.c	(working copy)
@@ -2305,6 +2305,12 @@ check_inquiry (gfc_expr *e, int not_rest
 	      && ap->expr->expr_type != EXPR_VARIABLE
 	      && check_restricted (ap->expr) == FAILURE)
 	  return MATCH_ERROR;
+
+	if (not_restricted == 0
+	    && ap->expr->expr_type == EXPR_VARIABLE
+	    && ap->expr->symtree->n.sym->attr.optional 
+	    && ap->expr->symtree->n.sym->attr.dummy)
+	  return MATCH_NO;
     }
 
   return MATCH_YES;
