Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Addition - fun - not what I thought
Message
De
05/07/2009 09:41:55
Cetin Basoz
Engineerica Inc.
Izmir, Turquie
 
 
À
05/07/2009 09:10:58
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Versions des environnements
Environment:
C# 3.0
Divers
Thread ID:
01410144
Message ID:
01410146
Vues:
67
>Following code
>
>I thought I would get 9 but I get 7
>
>	int i = 1;
>
>	i += (i += 2) + 3;
>
>	Console.WriteLine("{0}", i);
>	Console.ReadLine();
>
>
>Reason:
>The value of i is loaded at the beginning of the operation and not at the end just before the addition is done
>
>
>  .locals init ([0] int32 i)
>  IL_0000:  nop
>  IL_0001:  ldc.i4.1
>  IL_0002:  stloc.0   
>  IL_0003:  ldloc.0    // load i  for the first +=
>  IL_0004:  ldloc.0   // load i   for the second +=
>  IL_0005:  ldc.i4.2 
>  IL_0006:  add     
>  IL_0007:  dup
>  IL_0008:  stloc.0   // this is (i += 2) that is stored in i
>  IL_0009:  ldc.i4.3
>  IL_000a:  add
>  IL_000b:  add    // this is the original value of i, loaded in IL_0003
>  IL_000c:  stloc.0  // i is overwritten
>
>
>But this gives 9
>
>	int i = 1;
>
>	i += 2;
>	i += i + 3;
>
>
>
>IL_0000:  nop
>  IL_0001:  ldc.i4.1
>  IL_0002:  stloc.0
>  IL_0003:  ldloc.0
>  IL_0004:  ldc.i4.2
>  IL_0005:  add
>  IL_0006:  stloc.0
>  IL_0007:  ldloc.0
>  IL_0008:  ldloc.0
>  IL_0009:  ldc.i4.3
>  IL_000a:  add
>  IL_000b:  add
>  IL_000c:  stloc.0
>
Exactly the results I would expect,
int i = 1;
i += (i += 2) + 3;
is same as writing:
int i = 1;
i = i + (i = i + 2) + 3; // i = 1 + ( 1+2 ) + 3
and
int i = 1;
i += 2;
i += i + 3;
is same as writing:
int i = 1;
i = i + 2; // i = 3
i = i + i + 3; // i = 3+3+3
Cetin
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform