It doesn't compile, why?

#include <iostream>
#include <string>

using namespace std;

int main()
{
	
	for(int cnt1 = 0, int cnt2 = 10;  cnt1<10; ++cnt1, --cnt2)
	{
		cout << cnt1 << "--------Hello!---------" << cnt2 << endl;
	}
	
	system("PAUSE");
}

Dani AI

Generated

Small, common syntax mistake — the for initializer allows a single declaration with multiple declarators, but the type keyword appears only once. The correct pattern is, for example, for (int i = 0, j = 10; i < 10; ++i, --j) — not int repeated for the second variable. That extra int is what makes the compiler choke. As suggested, it really was just a simple typo; also correctly flagged the loop usage.

A few practical notes that often help newcomers:

  • Variables declared in the for initializer are scoped to the loop. If you need a counter after the loop, declare it before the loop instead.
  • If the two values need different types, declare them separately before the loop (you cannot mix types in a single declaration).
  • The comma in the declaration part separates declarators; the comma in the increment part separates expressions (the latter uses the comma operator, evaluated left-to-right).

On the runtime pause: is right to call attention to the system usage. Calling the shell is platform-specific and may require <cstdlib>; prefer a portable approach such as std::cin.get() (or simply run the program from a console) to avoid portability and security issues.

Recommended Answers

All 5 Replies

Sorry solved the problem myself

Good. Cuz the answer would've been "Because you wrote it wrong"

Without details, and our lack of psychic ability, what else could we say?

Without details, and our lack of psychic ability, what else could we say?

I could say:
1. the declaration of the variables in the loop is wrong, there's an int to many.

2. <cstdlib> has to be included for system() ;)

wrong usage of for loop

:icon_razz: back....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.