Order of the value of the printf function

Source: Internet
Author: User

After learning C language for so long, I did not expect to have a good understanding of the common printf functions in C language.

The following sections are available:

Set int arr [] = {6, 7, 8, 9, 10 };

Int * PTR = arr;

* (PTR ++) + = 123;

Printf ("% d, % d", * PTR, * (++ PTR ));

Why is the answer: 8, 8?

This is a Huawei interview question.

The key to this question is the operation sequence of printf.

Printf parameter. The function printf reads data from left to right, then puts the read data first to the bottom of the stack, and the last read data to the top of the stack. The processing starts from the top of the stack, all processed from the right.

 

This is a relatively difficult problem. The main test is I ++ and ++ I:

One by one analysis:
Int arr [] = {6, 7, 8, 9, 10 };

Int * PTR = arr;
// PTR is the first address of the array.

* (PTR ++) + = 123;
// Split it.
// 1. The first is PTR ++. At this time, we will focus on the latter ++, that is, the returned PTR is the original PTR value, that is, the first address of arr.
// This sentence is converted to a [0] + = 123, that is, after the calculation, a [0] = 129
// 2. After the entire sentence is run, PTR is truly ++. That is to say, at this time, the second position of the array pointed by PTR, that is, 7

Printf ("% d, % d", * PTR, * (++ PTR ));
// There is a function parameter entry sequence in this sentence. Generally, the VC compiler writes data from right to left into the stack, so this operation naturally goes from right to left.
// After ++ PTR, the PTR moves to another position, that is, a [2], 8.
// The * PTR above is 8, so after this sentence is run, the output is 8 or 8.

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.