while(*a++ == *b++) 11 May, 2010 while(*a++ == *b++)

Among the most elegant implementations is the string copy function (assuming you have allocated enough memory in the dest buffer):

//Assuming for elegance you don't have to return the number of bytes copied.
void strcpy(char* src, char* dest){
while(*dest++ = *src++);
}


But I have often wondered what happens at the assembler such *s gets you only a single byte/character. So here is a simple program that explores this - but in string compare:

int main(){
    char *a="String One", *b="String Two";
    while(*a++==*b++);
return 0;
}


I compiled this with ‘gcc -S’ option and got the following assembly code:

        
    .file	"testpointer.c"
	.def	___main;	.scl	2;	.type	32;	.endef
	.section .rdata,"dr"
LC0:
	.ascii "a\0"
LC1:
	.ascii "b\0"
	.text
.globl _main
	.def	_main;	.scl	2;	.type	32;	.endef
_main:
	pushl	%ebp
	movl	%esp, %ebp
	andl	$-16, %esp
	subl	$16, %esp
	call	___main
	movl	$LC0, 8(%esp)
	movl	$LC1, 12(%esp)
L2:
	movl	8(%esp), %eax
	movb	(%eax), %dl
	movl	12(%esp), %eax
	movb	(%eax), %al
	cmpb	%al, %dl
	sete	%al
	incl	8(%esp)
	incl	12(%esp)
	testb	%al, %al
	jne	L2
	movl	$0, %eax
	leave
	ret


Line 24: “cmpb %al, %dl” says it all. compare Lower Byte of register ‘a’ and register ‘d’. Now I can be in peace ;)



References:

  1. http://www.codeguru.com/cpp/cpp/cpp_mfc/tutorials/article.php/c9415


  1. http://www3.itu.edu.tr/~kesgin/mul06/intel/instr/sete_setz.html


  1. http://homepage.mac.com/randyhyde/webster.cs.ucr.edu/www.artofasm.com/DOS/ch09/CH09-6.html#HEADING6-83


Tags  ·   C programming  ·   Show Comments ▾


     
Original design for Tumblr crafted by Prashanth Kamalakanthan.
Adapted for Tumblr & Jekyll by Sai Charan. Customized theme available on Github.

Sai Charan's blog by Sai Charan is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
Creative Commons License