Exploring printf function Behavior

Source: Internet
Author: User

The C compiler does not have uniform regulations on some behaviors, and programmers cannot pray that the compiler will always understand the program according to your ideas. Therefore, when writing high-quality code, if you have doubts, it is best to use another safe way.

During programming, a printf ("% d", a, a ++) Statement is run. The initial value of variable A is 2, this statement prints 3 and 2, which makes me puzzled for a long time.

Later, through experiments, I understood how GCC works (other compilers do not have to go deep into it, but the style of writing code needs to be refined)

Printf scans from right to left, and then outputs from left to right! The process can be understood as follows:
Printf ("% d/n % d", a, a ++ );
From right to left: A ++ // push
2, A + 1
A // Push 3
Output: POP 3 // print 3
Pop
2 // print 2

 

Later, I wrote a program experiment again:

# Include <stdio. h> <br/> int fun1 () <br/>{< br/> printf ("fun1/N"); <br/> return 1; <br/>}< br/> int fun2 () <br/>{< br/> printf ("fun2/N"); <br/> return 2; <br/>}< br/> void main () <br/>{< br/> int A = 2; <br/> printf ("% d/N", ++ a, a); <br/> printf ("% d/N ", fun1 (), fun2 (); <br/>}

 

Conclusion: this problem does not need to be further investigated, but in order to avoid another error, you must temper your encoding style.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.