Question about memory allocation for variables

Hello guys,

if I have this function in runtime:

1
2
3
4
5
6
7
8
9
void foo (int x)
{
	if ( x == 5 ) // or any other sentence
		return; // or throw something, whatever
	
	int var;
	
	// do something with 'var', for the first time (of course)
}


and the "if" sentence is true, WILL 'var' be allocated in memory, OR 'var' was already allocated in memory before checking the "if" sentence?

This question is because I would like to avoid this extra work of allocating a variable that won't be used for anything, if it's possible.

Thanks in advance for any answers!
Last edited on
The object won't be created before it's declared, that's all that matters. However, the creation of an int has no side effects anyway.

Everything else is up to the compiler and the optimizations it performs. If you don't pass var's address to an outside function, it might never be created on the stack at all, but kept in a register instead. Otherwise, compilers usually calculate the maximum possible stack usage during a function's execution and allocate it all in one step at the beginning. Stack allocation essentially costs nothing, unlike heap allocation.
Last edited on
So worth it? Declaring variables AFTER these "returning/throwing ifs"?
It makes no difference in this case. However, you shouldn't declare variables before you actually need them, so yes, this is where it belongs.
Thanks!
Some gcc assembler output to emphasize the point:

1
2
3
4
5
6
7
void foo (int x)
{
	if ( x == 5 )return;
	int var;
	void bar(int);
	bar(var);
}

translates to:

1
2
3
4
5
6
7
8
_Z3fooi:
	cmpl	$5, %edi
	je	.L3
	xorl	%edi, %edi ;no stack allocation - 0 is passed to bar
	jmp	_Z3bari
.L3:
	rep
	ret


1
2
3
4
5
6
7
void foo (int x)
{
	if ( x == 5 )return;
	int var;
	void bar(int&);
	bar(var);
}

translates to:

1
2
3
4
5
6
7
8
9
_Z3fooi:                    ;the compiler does not care where you declare var
	subq	$24, %rsp   ;the stack pointer is adjusted once in the beginning
	cmpl	$5, %edi
	je	.L3
	leaq	12(%rsp), %rdi
	call	_Z3barRi
.L3:
	addq	$24, %rsp
	ret
Topic archived. No new replies allowed.