Here is my c function:
bool equalA = true; for (int i = 0; i < 4; i++) { if (str[i] != 'a') { equalA = false; } } if (equalA == true) { if(str.compare(4, 6, "matches")) { printf("%s", "matches\n"); } } Here is the patial assembly code:
movzbl (%rax), %eax cmpb $97, %al setne %al testb %al, %al je .L5 movb $0, -981(%rbp) .L5: addl $1, -980(%rbp) jmp .L6 The code above checks str[i] with 'a', if not equal, movb set equalA to false. If equal, jump to .L5. and continue for loop.
My question is: Shouldn't
cmpb $97, %al je .L5 would do the same work?
if str[i] == 'a', zflag will be set, je .L5 would take the branch. if str[i] != 'a', zflag will be cleared. je .L5 would not take the branch.
Why Compiler generates two lines of extra code after cmpb instruction?
boolresult of the comparison into a register and then test it. It already had to store it to memory because of-O0.