SDL: Fix -Wdeclaration-after-statement warnings

From 248cb3ca9cea83f2ef2fddf4610e6507cc2b55e3 Mon Sep 17 00:00:00 2001
From: Anonymous Maarten <[EMAIL REDACTED]>
Date: Mon, 12 Aug 2024 20:02:43 +0200
Subject: [PATCH] Fix -Wdeclaration-after-statement warnings

---
 .github/workflows/main.yml                |  1 +
 src/audio/coreaudio/SDL_coreaudio.m       |  3 ++-
 src/hidapi/ios/hid.m                      | 24 ++++++++++++++--------
 src/joystick/iphoneos/SDL_mfijoystick.m   |  4 ++--
 src/power/uikit/SDL_syspower.m            |  2 +-
 src/video/uikit/SDL_uikitappdelegate.m    | 14 +++++++++----
 src/video/uikit/SDL_uikitevents.m         | 25 +++++++++++++----------
 src/video/uikit/SDL_uikitmessagebox.m     |  2 +-
 src/video/uikit/SDL_uikitmodes.m          | 17 +++++++++------
 src/video/uikit/SDL_uikitopenglview.m     | 10 ++++++---
 src/video/uikit/SDL_uikitvideo.m          | 11 +++++++---
 src/video/uikit/SDL_uikitview.m           | 22 +++++++++++++-------
 src/video/uikit/SDL_uikitviewcontroller.m | 17 +++++++++++----
 src/video/uikit/SDL_uikitwindow.m         | 17 +++++++++------
 14 files changed, 112 insertions(+), 57 deletions(-)

diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 7198dfb8bddc8..89633eeb8ecdd 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -30,6 +30,7 @@ jobs:
         - { name: Ubuntu 22.04 (CMake),           os: ubuntu-22.04,   shell: sh }
         - { name: Ubuntu 22.04 (autotools),       os: ubuntu-22.04,   shell: sh,    autotools: true }
         - { name: iOS (CMake),                    os: macos-latest,   shell: sh,    cmake: '-DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_ARCHITECTURES="arm64"', cross: true, test-pkg-config: false }
+        - { name: tvOS (CMake),                    os: macos-latest,   shell: sh,    cmake: '-DCMAKE_SYSTEM_NAME=tvOS -DCMAKE_OSX_ARCHITECTURES="arm64"', cross: true, test-pkg-config: false }
         - { name: MacOS (CMake),                  os: macos-latest,   shell: sh,    cmake: '-DCMAKE_OSX_ARCHITECTURES="x86_64;arm64"' }
         - { name: MacOS (autotools),              os: macos-latest,   shell: sh,    autotools: true }
 
diff --git a/src/audio/coreaudio/SDL_coreaudio.m b/src/audio/coreaudio/SDL_coreaudio.m
index ab03f907e07e0..aaabeaae54c3b 100644
--- a/src/audio/coreaudio/SDL_coreaudio.m
+++ b/src/audio/coreaudio/SDL_coreaudio.m
@@ -455,12 +455,13 @@ static BOOL update_audio_session(_THIS, SDL_bool open, SDL_bool allow_playandrec
 
         if ((open_playback_devices || open_capture_devices) && !session_active) {
             if (![session setActive:YES error:&err]) {
+                NSString *desc;
                 if ([err code] == AVAudioSessionErrorCodeResourceNotAvailable &&
                     category == AVAudioSessionCategoryPlayAndRecord) {
                     return update_audio_session(this, open, SDL_FALSE);
                 }
 
-                NSString *desc = err.description;
+                desc = err.description;
                 SDL_SetError("Could not activate Audio Session: %s", desc.UTF8String);
                 return NO;
             }
diff --git a/src/hidapi/ios/hid.m b/src/hidapi/ios/hid.m
index 636d0f07696da..72879f2b072e1 100644
--- a/src/hidapi/ios/hid.m
+++ b/src/hidapi/ios/hid.m
@@ -290,6 +290,8 @@ - (int)updateConnectedSteamControllers:(BOOL) bForce
 {
 	static uint64_t s_unLastUpdateTick = 0;
 	static mach_timebase_info_data_t s_timebase_info;
+	uint64_t ticksNow;
+	NSArray<CBPeripheral *> *peripherals;
 
 	if ( self.centralManager == nil )
     {
@@ -301,7 +303,7 @@ - (int)updateConnectedSteamControllers:(BOOL) bForce
 		mach_timebase_info( &s_timebase_info );
 	}
 
-	uint64_t ticksNow = mach_approximate_time();
+	ticksNow = mach_approximate_time();
 	if ( !bForce && ( ( (ticksNow - s_unLastUpdateTick) * s_timebase_info.numer ) / s_timebase_info.denom ) < (5ull * NSEC_PER_SEC) )
 		return (int)self.deviceMap.count;
 
@@ -318,7 +320,7 @@ - (int)updateConnectedSteamControllers:(BOOL) bForce
 	if ( self.nPendingPairs > 0 )
 		return (int)self.deviceMap.count;
 
-	NSArray<CBPeripheral *> *peripherals = [self.centralManager retrieveConnectedPeripheralsWithServices: @[ [CBUUID UUIDWithString:@"180A"]]];
+	peripherals = [self.centralManager retrieveConnectedPeripheralsWithServices: @[ [CBUUID UUIDWithString:@"180A"]]];
 	for ( CBPeripheral *peripheral in peripherals )
 	{
 		// we already know this peripheral
@@ -328,8 +330,9 @@ - (int)updateConnectedSteamControllers:(BOOL) bForce
 		NSLog( @"connected peripheral: %@", peripheral );
 		if ( [peripheral.name isEqualToString:@"SteamController"] )
 		{
+			HIDBLEDevice *steamController;
 			self.nPendingPairs += 1;
-			HIDBLEDevice *steamController = [[HIDBLEDevice alloc] initWithPeripheral:peripheral];
+			steamController = [[HIDBLEDevice alloc] initWithPeripheral:peripheral];
 			[self.deviceMap setObject:steamController forKey:peripheral];
 			[self.centralManager connectPeripheral:peripheral options:nil];
 		}
@@ -452,9 +455,10 @@ - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeri
 
 	if ( [localName isEqualToString:@"SteamController"] )
 	{
+		HIDBLEDevice *steamController;
 		NSLog( @"%@ : %@ - %@", log, peripheral, advertisementData );
 		self.nPendingPairs += 1;
-		HIDBLEDevice *steamController = [[HIDBLEDevice alloc] initWithPeripheral:peripheral];
+		steamController = [[HIDBLEDevice alloc] initWithPeripheral:peripheral];
 		[self.deviceMap setObject:steamController forKey:peripheral];
 		[self.centralManager connectPeripheral:peripheral options:nil];
 	}
@@ -851,11 +855,13 @@ int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
 	if ( ( vendor_id == 0 || vendor_id == VALVE_USB_VID ) &&
 	     ( product_id == 0 || product_id == D0G_BLE2_PID ) )
 	{
+		NSEnumerator<HIDBLEDevice *> *devices;
 		HIDBLEManager *bleManager = HIDBLEManager.sharedInstance;
 		[bleManager updateConnectedSteamControllers:false];
-		NSEnumerator<HIDBLEDevice *> *devices = [bleManager.deviceMap objectEnumerator];
+		devices = [bleManager.deviceMap objectEnumerator];
 		for ( HIDBLEDevice *device in devices )
 		{
+			struct hid_device_info *device_info;
 			// there are several brief windows in connecting to an already paired device and
 			// one long window waiting for users to confirm pairing where we don't want
 			// to consider a device ready - if we hand it back to SDL or another
@@ -873,7 +879,7 @@ int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
 				}
 				continue;
 			}
-			struct hid_device_info *device_info = (struct hid_device_info *)malloc( sizeof(struct hid_device_info) );
+			device_info = (struct hid_device_info *)malloc( sizeof(struct hid_device_info) );
 			memset( device_info, 0, sizeof(struct hid_device_info) );
 			device_info->next = root;
 			root = device_info;
@@ -947,12 +953,13 @@ int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char
 
 int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
 {
+	size_t written;
     HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
 
 	if ( !device_handle.connected )
 		return -1;
 
-	size_t written = [device_handle get_feature_report:data[0] into:data];
+	written = [device_handle get_feature_report:data[0] into:data];
 
 	return written == length-1 ? (int)length : (int)written;
 }
@@ -969,6 +976,7 @@ int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
 
 int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
 {
+	int result;
     HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
 
 	if ( !device_handle.connected )
@@ -978,7 +986,7 @@ int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t
 	{
 		NSLog( @"hid_read_timeout with non-zero wait" );
 	}
-	int result = (int)[device_handle read_input_report:data];
+	result = (int)[device_handle read_input_report:data];
 #if FEATURE_REPORT_LOGGING
 	NSLog( @"HIDBLE:hid_read_timeout (%d) [%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]", result,
 		  data[1], data[2], data[3], data[4], data[5], data[6],
diff --git a/src/joystick/iphoneos/SDL_mfijoystick.m b/src/joystick/iphoneos/SDL_mfijoystick.m
index 28ddca72348c4..0af89a60697f2 100644
--- a/src/joystick/iphoneos/SDL_mfijoystick.m
+++ b/src/joystick/iphoneos/SDL_mfijoystick.m
@@ -1278,6 +1278,8 @@ static void IOS_MFIJoystickUpdate(SDL_Joystick *joystick)
         }
 #if TARGET_OS_TV
         else if (controller.microGamepad) {
+            Uint8 buttons[joystick->nbuttons];
+            int button_count = 0;
             GCMicroGamepad *gamepad = controller.microGamepad;
 
             Sint16 axes[] = {
@@ -1289,8 +1291,6 @@ static void IOS_MFIJoystickUpdate(SDL_Joystick *joystick)
                 SDL_PrivateJoystickAxis(joystick, i, axes[i]);
             }
 
-            Uint8 buttons[joystick->nbuttons];
-            int button_count = 0;
             buttons[button_count++] = gamepad.buttonA.isPressed;
             buttons[button_count++] = gamepad.buttonX.isPressed;
             buttons[button_count++] = (device->pause_button_pressed > 0);
diff --git a/src/power/uikit/SDL_syspower.m b/src/power/uikit/SDL_syspower.m
index d366d6548cdf9..0d762b9a743f5 100644
--- a/src/power/uikit/SDL_syspower.m
+++ b/src/power/uikit/SDL_syspower.m
@@ -61,6 +61,7 @@ SDL_bool SDL_GetPowerInfo_UIKit(SDL_PowerState *state, int *seconds, int *percen
 #else  /* TARGET_OS_TV */
     @autoreleasepool {
         UIDevice *uidev = [UIDevice currentDevice];
+        const float level = uidev.batteryLevel;
 
         if (!SDL_UIKitLastPowerInfoQuery) {
             SDL_assert(uidev.isBatteryMonitoringEnabled == NO);
@@ -95,7 +96,6 @@ SDL_bool SDL_GetPowerInfo_UIKit(SDL_PowerState *state, int *seconds, int *percen
             break;
         }
 
-        const float level = uidev.batteryLevel;
         *percent = ((level < 0.0f) ? -1 : ((int)((level * 100) + 0.5f)));
     }
 #endif /* TARGET_OS_TV */
diff --git a/src/video/uikit/SDL_uikitappdelegate.m b/src/video/uikit/SDL_uikitappdelegate.m
index 8fd4c71014e1f..b7f48edb9a772 100644
--- a/src/video/uikit/SDL_uikitappdelegate.m
+++ b/src/video/uikit/SDL_uikitappdelegate.m
@@ -189,12 +189,14 @@ - (instancetype)init
 
 - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 {
+    NSString *screenname;
+    NSBundle *bundle;
     if (!(self = [super initWithNibName:nil bundle:nil])) {
         return nil;
     }
 
-    NSString *screenname = nibNameOrNil;
-    NSBundle *bundle = nibBundleOrNil;
+    screenname = nibNameOrNil;
+    bundle = nibBundleOrNil;
 
     /* A launch screen may not exist. Fall back to launch images in that case. */
     if (screenname) {
@@ -230,6 +232,10 @@ - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibB
         /* Xcode 5 introduced a dictionary of launch images in Info.plist. */
         if (launchimages) {
             for (NSDictionary *dict in launchimages) {
+#if !TARGET_OS_TV
+                UIInterfaceOrientationMask orientmask;
+                NSString *orientstring;
+#endif
                 NSString *minversion = dict[@"UILaunchImageMinimumOSVersion"];
                 NSString *sizestring = dict[@"UILaunchImageSize"];
 
@@ -247,8 +253,8 @@ - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibB
                 }
 
 #if !TARGET_OS_TV
-                UIInterfaceOrientationMask orientmask = UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;
-                NSString *orientstring = dict[@"UILaunchImageOrientation"];
+                orientmask = UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;
+                orientstring = dict[@"UILaunchImageOrientation"];
 
                 if (orientstring) {
                     if ([orientstring isEqualToString:@"PortraitUpsideDown"]) {
diff --git a/src/video/uikit/SDL_uikitevents.m b/src/video/uikit/SDL_uikitevents.m
index 938b70a7d7ff8..59e2eeef35eb4 100644
--- a/src/video/uikit/SDL_uikitevents.m
+++ b/src/video/uikit/SDL_uikitevents.m
@@ -110,10 +110,11 @@ - (void)applicationDidChangeStatusBarOrientation
 
 void SDL_iPhoneSetEventPump(SDL_bool enabled)
 {
-    UIKit_EventPumpEnabled = enabled;
-
     static SDL_LifecycleObserver *lifecycleObserver;
     static dispatch_once_t onceToken;
+
+    UIKit_EventPumpEnabled = enabled;
+
     dispatch_once(&onceToken, ^{
         lifecycleObserver = [SDL_LifecycleObserver new];
     });
@@ -122,10 +123,6 @@ void SDL_iPhoneSetEventPump(SDL_bool enabled)
 
 void UIKit_PumpEvents(_THIS)
 {
-    if (!UIKit_EventPumpEnabled) {
-        return;
-    }
-
     /* Let the run loop run for a short amount of time: long enough for
        touch events to get processed (which is important to get certain
        elements of Game Center's GKLeaderboardViewController to respond
@@ -133,9 +130,12 @@ touch events to get processed (which is important to get certain
        delay in the rest of the app.
     */
     const CFTimeInterval seconds = 0.000002;
+    SInt32 result;
+    if (!UIKit_EventPumpEnabled) {
+        return;
+    }
 
     /* Pump most event types. */
-    SInt32 result;
     do {
         result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, seconds, TRUE);
     } while (result == kCFRunLoopRunHandledSource);
@@ -159,13 +159,14 @@ touch events to get processed (which is important to get certain
 
 static void OnGCKeyboardConnected(GCKeyboard *keyboard) API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
 {
+    dispatch_queue_t queue;
     keyboard_connected = SDL_TRUE;
     keyboard.keyboardInput.keyChangedHandler = ^(GCKeyboardInput *kbrd, GCControllerButtonInput *key, GCKeyCode keyCode, BOOL pressed)
     {
         SDL_SendKeyboardKey(pressed ? SDL_PRESSED : SDL_RELEASED, (SDL_Scancode)keyCode);
     };
 
-    dispatch_queue_t queue = dispatch_queue_create( "org.libsdl.input.keyboard", DISPATCH_QUEUE_SERIAL );
+    queue = dispatch_queue_create( "org.libsdl.input.keyboard", DISPATCH_QUEUE_SERIAL );
     dispatch_set_target_queue( queue, dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 ) );
     keyboard.handlerQueue = queue;
 }
@@ -275,7 +276,7 @@ static void UpdateScrollDirection(void)
         /* Couldn't read the preference, assume natural scrolling direction */
         naturalScrollDirection = YES;
     }
-    if (naturalScrollDirection) {    
+    if (naturalScrollDirection) {
         mouse_scroll_direction = SDL_MOUSEWHEEL_FLIPPED;
     } else {
         mouse_scroll_direction = SDL_MOUSEWHEEL_NORMAL;
@@ -307,6 +308,8 @@ static void OnGCMouseButtonChanged(SDL_MouseID mouseID, Uint8 button, BOOL press
 
 static void OnGCMouseConnected(GCMouse *mouse) API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
 {
+    int auxiliary_button;
+    dispatch_queue_t queue;
     SDL_MouseID mouseID = mice_connected;
 
     mouse.mouseInput.leftButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed)
@@ -322,7 +325,7 @@ static void OnGCMouseConnected(GCMouse *mouse) API_AVAILABLE(macos(11.0), ios(14
         OnGCMouseButtonChanged(mouseID, SDL_BUTTON_RIGHT, pressed);
     };
 
-    int auxiliary_button = SDL_BUTTON_X1;
+    auxiliary_button = SDL_BUTTON_X1;
     for (GCControllerButtonInput *btn in mouse.mouseInput.auxiliaryButtons) {
         btn.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed)
         {
@@ -355,7 +358,7 @@ static void OnGCMouseConnected(GCMouse *mouse) API_AVAILABLE(macos(11.0), ios(14
     };
     UpdateScrollDirection();
 
-    dispatch_queue_t queue = dispatch_queue_create( "org.libsdl.input.mouse", DISPATCH_QUEUE_SERIAL );
+    queue = dispatch_queue_create( "org.libsdl.input.mouse", DISPATCH_QUEUE_SERIAL );
     dispatch_set_target_queue( queue, dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 ) );
     mouse.handlerQueue = queue;
 
diff --git a/src/video/uikit/SDL_uikitmessagebox.m b/src/video/uikit/SDL_uikitmessagebox.m
index b68c0657e092f..b3eaefc46b870 100644
--- a/src/video/uikit/SDL_uikitmessagebox.m
+++ b/src/video/uikit/SDL_uikitmessagebox.m
@@ -56,12 +56,12 @@ static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messag
     int __block clickedindex = messageboxdata->numbuttons;
     UIWindow *window = nil;
     UIWindow *alertwindow = nil;
+    UIAlertController *alert;
 
     if (![UIAlertController class]) {
         return NO;
     }
 
-    UIAlertController *alert;
     alert = [UIAlertController alertControllerWithTitle:@(messageboxdata->title)
                                                 message:@(messageboxdata->message)
                                          preferredStyle:UIAlertControllerStyleAlert];
diff --git a/src/video/uikit/SDL_uikitmodes.m b/src/video/uikit/SDL_uikitmodes.m
index 47723070a1411..06781d2efb908 100644
--- a/src/video/uikit/SDL_uikitmodes.m
+++ b/src/video/uikit/SDL_uikitmodes.m
@@ -34,13 +34,17 @@ @implementation SDL_DisplayData
 - (instancetype)initWithScreen:(UIScreen*)screen
 {
     if (self = [super init]) {
+        NSDictionary* devices;
+        struct utsname systemInfo;
+        NSString* deviceName;
+        id foundDPI;
         self.uiscreen = screen;
 
         /*
          * A well up to date list of device info can be found here:
          * https://github.com/lmirosevic/GBDeviceInfo/blob/master/GBDeviceInfo/GBDeviceInfo_iOS.m
          */
-        NSDictionary* devices = @{
+        devices = @{
             @"iPhone1,1": @163,
             @"iPhone1,2": @163,
             @"iPhone2,1": @163,
@@ -138,11 +142,10 @@ - (instancetype)initWithScreen:(UIScreen*)screen
             @"iPod9,1": @326,
         };
 
-        struct utsname systemInfo;
         uname(&systemInfo);
-        NSString* deviceName =
+        deviceName =
             [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
-        id foundDPI = devices[deviceName];
+        foundDPI = devices[deviceName];
         if (foundDPI) {
             self.screenDPI = (float)[foundDPI integerValue];
         } else {
@@ -296,6 +299,7 @@ int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event)
     CGSize size = uiscreen.bounds.size;
     SDL_VideoDisplay display;
     SDL_DisplayMode mode;
+    SDL_DisplayData *data;
     SDL_zero(mode);
 
     /* Make sure the width/height are oriented correctly */
@@ -319,7 +323,7 @@ int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event)
     display.current_mode = mode;
 
     /* Allocate the display data */
-    SDL_DisplayData *data = [[SDL_DisplayData alloc] initWithScreen:uiscreen];
+    data = [[SDL_DisplayData alloc] initWithScreen:uiscreen];
     if (!data) {
         UIKit_FreeDisplayModeData(&display.desktop_mode);
         return SDL_OutOfMemory();
@@ -494,10 +498,11 @@ int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * r
 
 void UIKit_QuitModes(_THIS)
 {
+    int i, j;
+
     [SDL_DisplayWatch stop];
 
     /* Release Objective-C objects, so higher level doesn't free() them. */
-    int i, j;
     @autoreleasepool {
         for (i = 0; i < _this->num_displays; i++) {
             SDL_VideoDisplay *display = &_this->displays[i];
diff --git a/src/video/uikit/SDL_uikitopenglview.m b/src/video/uikit/SDL_uikitopenglview.m
index 145e8673fbf42..844396199de19 100644
--- a/src/video/uikit/SDL_uikitopenglview.m
+++ b/src/video/uikit/SDL_uikitopenglview.m
@@ -74,6 +74,7 @@ - (instancetype)initWithFrame:(CGRect)frame
         const BOOL useStencilBuffer = (stencilBits != 0);
         const BOOL useDepthBuffer = (depthBits != 0);
         NSString *colorFormat = nil;
+        CAEAGLLayer *eaglLayer;
 
         context = glcontext;
         samples = multisamples;
@@ -105,7 +106,7 @@ - (instancetype)initWithFrame:(CGRect)frame
             colorBufferFormat = GL_RGB565;
         }
 
-        CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
+        eaglLayer = (CAEAGLLayer *)self.layer;
 
         eaglLayer.opaque = YES;
         eaglLayer.drawableProperties = @{
@@ -315,10 +316,13 @@ - (void)swapBuffers
 
 - (void)layoutSubviews
 {
+    int width;
+    int height;
+
     [super layoutSubviews];
 
-    int width  = (int) (self.bounds.size.width * self.contentScaleFactor);
-    int height = (int) (self.bounds.size.height * self.contentScaleFactor);
+    width  = (int) (self.bounds.size.width * self.contentScaleFactor);
+    height = (int) (self.bounds.size.height * self.contentScaleFactor);
 
     /* Update the color and depth buffer storage if the layer size has changed. */
     if (width != backingWidth || height != backingHeight) {
diff --git a/src/video/uikit/SDL_uikitvideo.m b/src/video/uikit/SDL_uikitvideo.m
index f3257ea3f5614..f23b5d31bcb83 100644
--- a/src/video/uikit/SDL_uikitvideo.m
+++ b/src/video/uikit/SDL_uikitvideo.m
@@ -198,6 +198,11 @@ CGRect UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen)
 {
     SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
     CGRect frame = screen.bounds;
+#if !TARGET_OS_TV
+    UIInterfaceOrientation orient;
+    BOOL landscape;
+    BOOL fullscreen;
+#endif
 
     /* Use the UIWindow bounds instead of the UIScreen bounds, when possible.
      * The uiwindow bounds may be smaller than the screen bounds when Split View
@@ -215,10 +220,10 @@ CGRect UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen)
      * https://bugzilla.libsdl.org/show_bug.cgi?id=3505
      * https://bugzilla.libsdl.org/show_bug.cgi?id=3465
      * https://forums.developer.apple.com/thread/65337 */
-    UIInterfaceOrientation orient = [UIApplication sharedApplication].statusBarOrientation;
-    BOOL landscape = UIInterfaceOrientationIsLandscape(orient) ||
+    orient = [UIApplication sharedApplication].statusBarOrientation;
+    landscape = UIInterfaceOrientationIsLandscape(orient) ||
                     !(UIKit_GetSupportedOrientations(window) & (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown));
-    BOOL fullscreen = CGRectEqualToRect(screen.bounds, frame);
+    fullscreen = CGRectEqualToRect(screen.bounds, frame);
 
     /* The orientation flip doesn't make sense when the window is smaller
      * than the screen (iPad Split View, for example). */
diff --git a/src/video/uikit/SDL_uikitview.m b/src/video/uikit/SDL_uikitview.m
index 63afa0942bbb9..c63fa9b3c70b2 100644
--- a/src/video/uikit/SDL_uikitview.m
+++ b/src/video/uikit/SDL_uikitview.m
@@ -53,20 +53,25 @@ - (instancetype)initWithFrame:(CGRect)frame
 {
     if ((self = [super initWithFrame:frame])) {
 #if TARGET_OS_TV
+        UISwipeGestureRecognizer *swipeUp;
+        UISwipeGestureRecognizer *swipeDown;
+        UISwipeGestureRecognizer *swipeLeft;
+        UISwipeGestureRecognizer *swipeRight;
+
         /* Apple TV Remote touchpad swipe gestures. */
-        UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
+        swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
         swipeUp.direction = UISwipeGestureRecognizerDirectionUp;
         [self addGestureRecognizer:swipeUp];
 
-        UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
+        swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
         swipeDown.direction = UISwipeGestureRecognizerDirectionDown;
         [self addGestureRecognizer:swipeDown];
 
-        UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
+        swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
         swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
         [self addGestureRecognizer:swipeLeft];
 
-        UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
+        swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
         swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
         [self addGestureRecognizer:swipeRight];
 #endif
@@ -257,6 +262,7 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
         }
 #endif
         if (!handled) {
+            CGPoint locationInView;
             SDL_TouchDeviceType touchType = [self touchTypeForTouch:touch];
             SDL_TouchID touchId = [self touchIdForType:touchType];
             float pressure = [self pressureForTouch:touch];
@@ -267,7 +273,7 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 
             /* FIXME, need to send: int clicks = (int) touch.tapCount; ? */
 
-            CGPoint locationInView = [self touchLocation:touch shouldNormalize:YES];
+            locationInView = [self touchLocation:touch shouldNormalize:YES];
             SDL_SendTouch(touchId, (SDL_FingerID)((size_t)touch), sdlwindow,
                           SDL_TRUE, locationInView.x, locationInView.y, pressure);
         }
@@ -312,6 +318,7 @@ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
         }
 #endif
         if (!handled) {
+            CGPoint locationInView;
             SDL_TouchDeviceType touchType = [self touchTypeForTouch:touch];
             SDL_TouchID touchId = [self touchIdForType:touchType];
             float pressure = [self pressureForTouch:touch];
@@ -322,7 +329,7 @@ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
 
             /* FIXME, need to send: int clicks = (int) touch.tapCount; ? */
 
-            CGPoint locationInView = [self touchLocation:touch shouldNormalize:YES];
+            locationInView = [self touchLocation:touch shouldNormalize:YES];
             SDL_SendTouch(touchId, (SDL_FingerID)((size_t)touch), sdlwindow,
                           SDL_FALSE, locationInView.x, locationInView.y, pressure);
         }
@@ -348,6 +355,7 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
         }
 #endif
         if (!handled) {
+            CGPoint locationInView;
             SDL_TouchDeviceType touchType = [self touchTypeForTouch:touch];
             SDL_TouchID touchId = [self touchIdForType:touchType];
             float pressure = [self pressureForTouch:touch];
@@ -356,7 +364,7 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
                 continue;
             }
 
-            CGPoint locationInView = [self touchLocation:touch shouldNormalize:YES];
+            locationInView = [self touchLocation:touch shouldNormalize:YES];
             SDL_SendTouchMotion(touchId, (SDL_FingerID)((size_t)touch), sdlwindow,
                                 locationInView.x, locationInView.y, pressure);
         }
diff --git a/src/video/uikit/SDL_uikitviewcontroller.m b/src/video/uikit/SDL_uikitviewcontroller.m
index 0d8052b7f02bf..432033a8cbee0 100644
--- a/src/video/uikit/SDL_uikitviewcontroller.m
+++ b/src/video/uikit/SDL_uikitviewcontroller.m
@@ -158,10 +158,14 @@ - (void)setAnimationCallback:(int)interval
 
 - (void)startAnimation
 {
+#ifdef __IPHONE_10_3
+    SDL_WindowData *data;
+#endif
+
     displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(doLoop:)];
 
 #ifdef __IPHONE_10_3
-    SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+    data = (__bridge SDL_WindowData *) window->driverdata;
 
     if ([displayLink respondsToSelector:@selector(preferredFramesPerSecond)]
         && data != nil && data.uiwindow != nil
@@ -269,6 +273,7 @@ - (BOOL)prefersPointerLocked
 /* Set ourselves up as a UITextFieldDelegate */
 - (void)initKeyboard
 {
+    NSNotificationCenter *center;
     obligateForBackspace = @"                                                                "; /* 64 space */
     textField = [[SDLUITextField alloc] initWithFrame:CGRectZero];
     textField.delegate = self;
@@ -288,7 +293,7 @@ - (void)initKeyboard
     textField.hidden = YES;
     keyboardVisible = NO;
 
-    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
+    center = [NSNotificationCenter defaultCenter];
 #if !TARGET_OS_TV
     [center addObserver:self
                selector:@selector(keyboardWillShow:)
@@ -415,6 +420,9 @@ - (void)hideKeyboard
 - (void)keyboardWillShow:(NSNotification *)notification
 {
     BOOL shouldStartTextInput = NO;
+#if !TARGET_OS_TV
+    CGRect kbrect;
+#endif
 
     if (!SDL_IsTextInputActive() && !hidingKeyboard && !rotatingOrientation) {
         shouldStartTextInput = YES;
@@ -422,7 +430,7 @@ - (void)keyboardWillShow:(NSNotification *)notification
 
     showingKeyboard = YES;
 #if !TARGET_OS_TV
-    CGRect kbrect = [[notification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue];
+    kbrect = [[notification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue];
 
     /* The keyboard rect is in the coordinate space of the screen/window, but we
      * want its height in the coordinate space of the view. */
@@ -568,12 +576,13 @@ - (BOOL)textFieldShouldReturn:(UITextField*)_textField
 
 static SDL_uikitviewcontroller *GetWindowViewController(SDL_Window * window)
 {
+    SDL_WindowData *data;
     if (!window || !window->driverdata) {
         SDL_SetError("Invalid window");
         return nil;
     }
 
-    SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
+    data = (__bridge SDL_WindowData *)window->driverdata;
 
     return data.viewcontroller;
 }
diff --git a/src/video/uikit/SDL_uikitwindow.m b/src/video/uikit/SDL_uikitwindow.m
index df3f2d90d1041..41a6bbb9b8599 100644
--- a/src/video/uikit/SDL_uikitwindow.m
+++ b/src/video/uikit/SDL_uikitwindow.m
@@ -155,6 +155,10 @@ int UIKit_CreateWindow(_THIS, SDL_Window *window)
         SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
         SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
         SDL_Window *other;
+        UIWindow *uiwindow;
+#if !TARGET_OS_TV
+        const CGSize origsize = data.uiscreen.currentMode.size;
+#endif
 
         /* We currently only handle a single window per display on iOS */
         for (other = _this->windows; other; other = other->next) {
@@ -167,14 +171,13 @@ int UIKit_CreateWindow(_THIS, SDL_Window *window)
          * user, so it's in standby), try to force the display to a resolution
          * that most closely matches the desired window size. */
 #if !TARGET_OS_TV
-        const CGSize origsize = data.uiscreen.currentMode.size;
         if ((origsize.width == 0.0f) && (origsize.height == 0.0f)) {
+            int i;
+            const SDL_DisplayMode *bestmode = NULL;
             if (display->num_display_modes == 0) {
                 _this->GetDisplayModes(_this, display);
             }
 
-            int i;
-            const SDL_DisplayMode *bestmode = NULL;
             for (i = display->num_display_modes; i >= 0; i--) {
                 const SDL_DisplayMode *mode = &display->display_modes[i];
                 if ((mode->w >= window->w) && (mode->h >= window->h)) {
@@ -204,7 +207,7 @@ int UIKit_CreateWindow(_THIS, SDL_Window *window)
 
         /* ignore the size user requested, and make a fullscreen window */
         /* !!! FIXME: can we have a smaller view? */
-        UIWindow *uiwindow = [[SDL_uikitwindow alloc] initWithFrame:data.uiscreen.bounds];
+        uiwindow = [[SDL_uikitwindow alloc] initWithFrame:data.uiscreen.bounds];
 
         /* put the window on an

(Patch may be truncated, please check the link at the top of this post.)