Do you declare variables at the top of functions

Matrix code
Image by Pete Linforth from Pixabay

This is for C99 and later. Prior to this, in function you had to declare all the variables that would be used in that function before any code. Since C99, you can declare them nearer to where they are used.

This function is from the Asteroids game. The declaration of the two variables hx,hy could have been moved to just before the do-loop. They can’t be declared inside the do-loop because they are used after it.

// doHyperJump() find empty space on screen fo PlayerShip
void CheckJump() {
	int hx, hy;

	if (jumpFlag && SDL_GetTicks() - jumpTimer > 3000) { 
		jumpTimer = SDL_GetTicks();
		jumpFlag = 0;
		do {
			hx = 65 + Random(SCREENWIDTH - 130);
			hy = 65 + Random(SCREENHEIGHT - 130);
			if (IsEmptySpace(hx, hy)) break;
		} while (1);
		Player.x = (float)hx;
		Player.y = (float)hy;
		Player.vx = 0;
		Player.vy = 0;
	}
}

This is one of those cases where it doesn’t really matter. But generally I will declare them close to where they are first used and I almost always declare the for-loop variable in the for-loop. Only if it’s needed afterwards do I declare it after, but that is a slightly iffy use unless you want to check the value it had when it exited the loop.

Remember the scope of the variable i.e. the part of the function in which the variable can be accessed starts just after it is declared. By keeping declarations near the code, you reduce the scope and this can help robustness.

Leave a Reply

Your email address will not be published. Required fields are marked *