简体   繁体   中英

C# help declaring variable i initialize it to

I'd like to declare an int variable i , initialize it to 4 and then test the following increment and decrement statements. Comment on the obtained output.

Here is the incomplete code that I made:

    class Program
    {
        static void Main(string[] args)
        {
            int Cash;
            Cash = 10;

            Console.WriteLine("{0}", ++ Cash);
            Console.WriteLine("{0}", Cash);
            Console.WriteLine("{0}", Cash ++);
        }
    }

It gives me

11, 11 11

from the output. I'm not sure If I did it correct. Can someone please correct me if I'm wrong?

Yes, the output is correct:

// This line increments the variable then prints its value.
Console.WriteLine("{0}", ++ Cash);
// This prints the value of the (incremented variable)
Console.WriteLine("{0}", Cash);
// The prints the value of the variable *then* increments its value
Console.WriteLine("{0}", Cash ++);

Using var++ or ++var both increment your var value. If you use var++ on a writeline, system prints the value of the var before increment it.

If you want to decrement value from a var, use var--.

When you do ++Cash , it increments the variable first , then prints. After, you just print the variable, then on Cash++ it prints the variable before the increment. So yes your output is correct.

++cache= update variable and then take it


cache++ = take value and than update variable
int Cash;
Cash = 10;

Console.WriteLine("{0}", ++ Cash);
Console.WriteLine("{0}", Cash);
Console.WriteLine("{0}", Cash ++);

You initialize Cash to 10 (which should be lower case by the way). Then you preincrement before the WriteLine() is done. Thus it prints 11 . The next just prints out your cash variable which is at this point 11. Then you do a post increment see link... which prints out the cash variable and then increments it. If you writeLine() your cash variable now, it will be 12.

++ Cash is "Increase Cash by 1 and give it to me" - it will give you 11

Cash then is 11

Cash ++ is "Give me Cash and then increase it by 1" - it will give you 11 and then Cash will be 12.

Similar question: C# Pre- & Post Increment confusions

You will find alot of valuable information on the outputs you are obtaining here:

https://msdn.microsoft.com/en-us/library/36x43w8w.aspx

Short answer is that you are doing a pre increment and post increment operation there and thus are seeing the result AFTER the operation (in this case addition of one) - the value of the variable currently, and then the result BEFORE the operation. This is why you see 11 all three times.

cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM