C + + When a comma that defines a variable encounters a comma that is initialized with a for statement condition

Source: Internet
Author: User

The procedure is as follows:

#include <iostream>using std::cout;using std::endl;int main (int argc, char** argv) {int i = 0, j = 2;    for (int z = 2, i = J;z = = 2;z++) cout << "I:" << i << Endl; cout << "I:" << i << Endl;}

Output

i:2i:0

Analysis:

The first semicolon in the For statement is preceded by an initialization statement, and multiple initialization statements are separated by commas and separated by commas when defining multiple variables of the same type, so what happens when the two cases overlap.

If you press the format above

for (int z = 2, i = J;z = = 2;z++)

There are two kinds of conjecture at this time:

1, I for the new application, only valid in the FOR statement, the statement block local variables, with the J variable in the main function to initialize it, at this time it will block the main function of the I variable.

2, I is the main function I, where the value of the variable J in the main function is assigned to the I value in the I,main function is changed.


Both assumptions are based, but according to the output of the program, I is considered a new application of the statement block local variables.

It blocks I in the main function, where I in the main function has the same value. When the For statement finishes running, I in the main function, or the previous value.

C + + When a comma that defines a variable encounters a comma that is initialized with a for statement condition

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.