C语言之volatile用法(二十一),2021最新Android面试笔试题目分享

本文探讨了C语言中volatile关键字的作用,通过对比优化前后代码展示其避免编译器优化的效果,并通过Android面试题目解释volatile在多线程和硬件交互场景的重要性。示例代码展示了volatile如何影响循环优化,强调了在处理并发和硬件交互时使用volatile的必要性。
摘要由CSDN通过智能技术生成

int main (void)

{

int i = 10;

int a = i; //优化

int b = i;

printf (“i = %d\n”, b);

return 0;

}

//编译优化、查看汇编

gcc -O2 -S test.c

cat test.s

.file    “test.c”

.section    .rodata.str1.1,“aMS”,@progbits,1

.LC0:

.string    “i = %d\n”

.section    .text.startup,“ax”,@progbits

.p2align 4,15

.globl    main

.type    main, @function

main:

.LFB22:

.cfi_startproc

pushl    %ebp

.cfi_def_cfa_offset 8

.cfi_offset 5, -8

movl    %esp, %ebp

.cfi_def_cfa_register 5

andl    $-16, %esp

subl    $16, %esp

movl    $10, 8(%esp)

movl    $.LC0, 4(%esp)

movl    $1, (%esp)

call    __printf_chk

xorl    %eax, %eax

leave

.cfi_restore 5

.cfi_def_cfa 4, 4

ret

.cfi_endproc

.LFE22:

.size    main, .-main

.ident    “GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3”

.section    .note.GNU-stack,"",@progbits

//示例二

#include <stdio.h>

int main (void)

{

volatile int i = 10;

int a = i; //未优化

int b = i;

printf (“i = %d\n”, b);

return 0;

}

//编译优化、查看汇编

gcc -O2 -S test.c

cat test.s

.file    “test.c”

.section    .rodata.str1.1,“aMS”,@progbits,1

.LC0:

.string    “i = %d\n”

.section    .text.startup,“ax”,@progbits

.p2align 4,15

.globl    main

.type    main, @function

main:

.LFB22:

.cfi_startproc

pushl

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值