 src/interfaces/libpq/fe-connect.c | 51 +++++++++++++++------------------------
 1 file changed, 20 insertions(+), 31 deletions(-)

diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index edc324dad0..ef95b07978 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -4344,6 +4344,15 @@ select_next_encryption_method(PGconn *conn, bool have_valid_connection)
 {
 	int			remaining_methods;
 
+#define SELECT_NEXT_METHOD(method) \
+	do { \
+		if ((remaining_methods & method) != 0) \
+		{ \
+			conn->current_enc_method = method; \
+			return true; \
+		} \
+	} while (false)
+
 	remaining_methods = conn->allowed_enc_methods & ~conn->failed_enc_methods;
 
 	/*
@@ -4373,20 +4382,14 @@ select_next_encryption_method(PGconn *conn, bool have_valid_connection)
 				}
 			}
 		}
-		if ((remaining_methods & ENC_GSSAPI) != 0)
-		{
-			conn->current_enc_method = ENC_GSSAPI;
-			return true;
-		}
 	}
+
+	SELECT_NEXT_METHOD(ENC_GSSAPI);
 #endif
 
 	/* With sslmode=allow, try plaintext connection before SSL. */
-	if (conn->sslmode[0] == 'a' && (remaining_methods & ENC_PLAINTEXT) != 0)
-	{
-		conn->current_enc_method = ENC_PLAINTEXT;
-		return true;
-	}
+	if (conn->sslmode[0] == 'a')
+		SELECT_NEXT_METHOD(ENC_PLAINTEXT);
 
 	/*
 	 * Try SSL. If enabled, try direct SSL. Unless we have a valid TCP
@@ -4396,33 +4399,19 @@ select_next_encryption_method(PGconn *conn, bool have_valid_connection)
 	 * roundtrip from the negotiation, but reconnecting would also incur a
 	 * roundtrip.
 	 */
-	if (have_valid_connection && (remaining_methods & ENC_NEGOTIATED_SSL) != 0)
-	{
-		conn->current_enc_method = ENC_NEGOTIATED_SSL;
-		return true;
-	}
-
-	if ((remaining_methods & ENC_DIRECT_SSL) != 0)
-	{
-		conn->current_enc_method = ENC_DIRECT_SSL;
-		return true;
-	}
+	if (have_valid_connection)
+		SELECT_NEXT_METHOD(ENC_NEGOTIATED_SSL);
 
-	if ((remaining_methods & ENC_NEGOTIATED_SSL) != 0)
-	{
-		conn->current_enc_method = ENC_NEGOTIATED_SSL;
-		return true;
-	}
+	SELECT_NEXT_METHOD(ENC_DIRECT_SSL);
+	SELECT_NEXT_METHOD(ENC_NEGOTIATED_SSL);
 
-	if (conn->sslmode[0] != 'a' && (remaining_methods & ENC_PLAINTEXT) != 0)
-	{
-		conn->current_enc_method = ENC_PLAINTEXT;
-		return true;
-	}
+	if (conn->sslmode[0] != 'a')
+		SELECT_NEXT_METHOD(ENC_PLAINTEXT);
 
 	/* No more options */
 	conn->current_enc_method = ENC_ERROR;
 	return false;
+#undef SELECT_NEXT_METHOD
 }
 
 /*
