C++: Set bool value only if not set

后端 未结 6 2176
小鲜肉
小鲜肉 2020-12-17 22:19

I have code in my C++ application that generally does this:

bool myFlag = false;
while (/*some finite condition unrelated to myFlag*/) {
    if (...) {
               


        
6条回答
  •  悲&欢浪女
    2020-12-17 22:51

    This question gave me headache too so i simply tested it myself with the following code (C#):

            System.Diagnostics.Stopwatch time = new System.Diagnostics.Stopwatch();
            int i = 0;
            int j = 1;
    
            time.Start();
            if (i != 0)
                i = 0;
            time.Stop();
            Console.WriteLine("compare + set - {0} ticks", time.ElapsedTicks);
    
            time.Reset();
            time.Start();
            if (j != 0)
                j = 0;
            time.Stop();
            Console.WriteLine("compare - {0} ticks", time.ElapsedTicks);
    
    
            time.Reset();
            time.Start();
            i = 0;
            time.Stop();
            Console.WriteLine("set - {0} ticks", time.ElapsedTicks);
    
            Console.ReadLine();
    

    result:

    compare + set - 1 ticks

    compare - 1 ticks

    set - 0 ticks

    while the time, used to set the value surely isn't zero, it shows that even a single query needed more time than just setting the variable.

提交回复
热议问题