goto skips declaration of variable

nrgyzer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 21 04:12:36 PDT 2014


On Tuesday, 19 August 2014 at 20:33:00 UTC, monarch_dodra wrote:
> On Monday, 18 August 2014 at 13:51:14 UTC, nrgyzer wrote:
>> Hi all,
>>
>> I've the following code snipped:
>>
>> import std.bigint;
>> void main(string[] args)
>> {
>> 	BigInt i = "12345";
>> 	if (args.length > 1)
>> 	{
>> 		goto Exit;
>> 	}
>> 	i = BigInt("67890");
>> 	Exit:
>> 		return;
>> }
>
> For what it's worth, whenever you have "goto-end" style code, 
> place all your code in a proper block, in such a way that all 
> your variable declarations are in that block, and all your 
> gotos break out of this block. This way, a goto will *never* 
> cross a declaration, so coding is easy. The only variables you 
> place at the top or the ones that could need cleanup.
>
> void main(string[] args)
> {
> 	//Declarations that need cleanup:
> 	void* p;
>
> 	//Code
> 	{
> 		BigInt i = "12345"; //Local variable
> 		if (args.length > 1)
> 		{
> 			goto Exit; //Breaks out of block
> 		}
> 		i = BigInt("67890");
> 		BigInt j = "54321"; //Local variable
> 	}
>
> 	//End
> 	Exit:
> 		CleanUp(p);
> 		return;
> }

Yes, that works. I'm using the goto-command to exit my function
if an error (not necessarily an exception) occured. Sure, I can
simply do a return, but I personally prefer a fixed endpoint of
my functions. This also simplifies debugging my application
because I don't need 10 or 20 breakpoints (one before each
return-point).


More information about the Digitalmars-d-learn mailing list