首页 > 代码库 > 【C++】*p++ = *p不同环境下操作不同

【C++】*p++ = *p不同环境下操作不同

实测,Ubuntu16.04,gcc 5.3.0&5.4.0(编译选项选择C++11和不选择新标准结果相同)

#include<iostream>
using namespace std;

int main()
{
    int a[] = {1,2,3,4,5,6};
    int *p = a;
    for (int i = 0; i < 5; i++) {
        *(p++) = *p;
    }
    cout<<"===="<<endl;
    for (int i = 0; i < 5; i++) {
        cout << a[i] << endl;
    }
    cout <<  << endl;
    return 0;
}

输出为

2,3,4,5,6

  而同样的代码,在Windows下VS环境中,

输出为

1,2,3,4,5

  这个就很奇怪了,只能取看具体操作情况了,下面是汇编文件,有空填坑(g++ -S ex.cpp生成汇编文件)

#include<iostream>
using namespace std;

int main()
{
    int a[] = {1,2,3,4,5,6};
    int *p = a;
    for (int i = 0; i < 5; i++) {
        *(p++) = *p;
    }
    return 0;
}

  

	.file	"ex2.cpp"
	.local	_ZStL8__ioinit
	.comm	_ZStL8__ioinit,1,1
	.text
	.globl	main
	.type	main, @function
main:
.LFB1021:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	movl	$1, -48(%rbp)
	movl	$2, -44(%rbp)
	movl	$3, -40(%rbp)
	movl	$4, -36(%rbp)
	movl	$5, -32(%rbp)
	movl	$6, -28(%rbp)
	leaq	-48(%rbp), %rax
	movq	%rax, -8(%rbp)
	movl	$0, -12(%rbp)
.L3:
	cmpl	$4, -12(%rbp)
	jg	.L2
	movq	-8(%rbp), %rax
	leaq	4(%rax), %rdx
	movq	%rdx, -8(%rbp)
	movq	-8(%rbp), %rdx
	movl	(%rdx), %edx
	movl	%edx, (%rax)
	addl	$1, -12(%rbp)
	jmp	.L3
.L2:
	movl	$0, %eax
	popq	%rbp
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc
.LFE1021:
	.size	main, .-main
	.type	_Z41__static_initialization_and_destruction_0ii, @function
_Z41__static_initialization_and_destruction_0ii:
.LFB1022:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	subq	$16, %rsp
	movl	%edi, -4(%rbp)
	movl	%esi, -8(%rbp)
	cmpl	$1, -4(%rbp)
	jne	.L7
	cmpl	$65535, -8(%rbp)
	jne	.L7
	movl	$_ZStL8__ioinit, %edi
	call	_ZNSt8ios_base4InitC1Ev
	movl	$__dso_handle, %edx
	movl	$_ZStL8__ioinit, %esi
	movl	$_ZNSt8ios_base4InitD1Ev, %edi
	call	__cxa_atexit
.L7:
	nop
	leave
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc
.LFE1022:
	.size	_Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii
	.type	_GLOBAL__sub_I_main, @function
_GLOBAL__sub_I_main:
.LFB1023:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	movl	$65535, %esi
	movl	$1, %edi
	call	_Z41__static_initialization_and_destruction_0ii
	popq	%rbp
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc
.LFE1023:
	.size	_GLOBAL__sub_I_main, .-_GLOBAL__sub_I_main
	.section	.init_array,"aw"
	.align 8
	.quad	_GLOBAL__sub_I_main
	.hidden	__dso_handle
	.ident	"GCC: (GNU) 5.3.0"
	.section	.note.GNU-stack,"",@progbits

  

【C++】*p++ = *p不同环境下操作不同