Difference between while(1) and for(;;)

In programming, we often need to use infinite loops, two commonly used methods are while (1) and for (;;). Both methods work exactly the same, but which one is better? Let's take a look at their compiled code:

Before compiling:

while (1);

After compilation:

mov eax,1

test eax,eax

your foo+23h

jmp foo+18h

Before compiling:

for (;;);

After compilation:

jmp foo+23h

Obviously, for (;;) has fewer instructions, does not occupy registers, and has no judgment or jump, which is better than while (1). This is because the previous compilers have inconsistent compilation processing of these two kinds of wireless loops.

Third, the impact of modern compilers (gcc-4.1.1-52-e15) on these two wireless loops?

First look at for.c

int main()

{

   for(;;);

  return 0;

}

First look at while.c

intmain()

{

   while(1);

  return 0;

}

Compile with gcc

gcc –g –c for.c –o for.o

gcc –g –c while.c –o while.o

objdump –j .text –Sl while.o > while.txt

objdump –j .text –Sl for.o > for.txt

As a result, from the assembly point of view, the assembly codes of for(;;) and while(1) are both

4 : eb fe jmp 4

The conclusion is: their assembly instructions are the same, so the efficiency is the same

The while (1) infinite loop is often used in the programming of the single-chip microcomputer to perform the round-robin operation, but for (;;) is often seen as the condition of the infinite loop when analyzing the Linux kernel source code.

The difference between the two:

difference one

The two ;;s in the for(;;) infinite loop represent two empty statements, and the compiler will generally optimize them away and enter the loop body directly.

The 1 in the while(1) infinite loop is regarded as an expression, and every time the loop is to determine whether the constant 1 is equal to zero.

difference two

for.c source code:

include

include

Reprinted from: https://blog.csdn.net/nh5431313/article/details/68482778

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325732272&siteId=291194637