C++多指针初始化的for循环:如何避免重复书写指针符号*?
Block* Variables Without Repeating * in For Loop Got it, let's tackle this problem! You want to declare both a and b as Block* pointers in your for loop, but you don't want to write the * before b. First, let's clear up why the (Block*) a, b approach doesn't work—it's a common syntax gotcha in C++:
The
(Block*)here isn't a type specifier that applies to both variables. Instead, you're trying to castatoBlock*(which makes no sense in a declaration context) while leavingbwithout an explicit type. This will throw a compiler error, since C++ requires explicit type declarations for variables (unless usingauto).
Here are two clean, valid ways to achieve what you want:
1. Use a Type Alias
Create an alias for Block* so you can declare both variables without repeating the pointer syntax. You have two options for this:
// Option 1: typedef (works in all C++ versions) typedef Block* BlockPtr; // Option 2: using (modern C++ preferred, more readable) using BlockPtr = Block*; // Now use the alias in your loop for (BlockPtr a = aList, b = bList; a != nullptr; a = a->next, b = b->next) { if (a->data != b->data) { // Fixed your original code: compare current elements, not the list heads! cout << "Difference found.\n"; } }
Side note: I fixed a bug in your original code—you were comparing the first element of aList to bList every iteration, not the current elements a and b point to.
2. Use auto Type Deduction (C++11+)
If you're working with C++11 or newer, auto will automatically deduce the type of a and b from their initializers (aList and bList, which are Block*). This is the most concise approach:
for (auto a = aList, b = bList; a != nullptr; a = a->next, b = b->next) { if (a->data != b->data) { cout << "Difference found.\n"; } }
Both methods let you declare a and b as Block* without writing the * before b, and they're fully compliant with C++ standards.
内容的提问来源于stack exchange,提问作者Topological Sort

