Mixing Variable Types in for Loop Initialization
In C , can one declare variables of different data types within the initialization part of a for loop? For instance:
for (int i = 0, j = 0; ...
Can this syntax be modified to initialize an integer (int) alongside a character (char)? If so, how is this achieved?
Answer:
Directly declaring variables of different types within the initialization part of a for loop is not possible. However, there is a technical workaround, though its practical usage is questionable:
for (struct { int a; char b; } s = { 0, 'a' }; s.a < 5; ++s.a) { std::cout << s.a << " " << s.b << std::endl; }
This method uses a struct to create a single entity with both an integer and a character member, allowing for their simultaneous initialization.
The above is the detailed content of Can You Initialize Variables of Different Data Types in a C for Loop?. For more information, please follow other related articles on the PHP Chinese website!