Variables can be declared and initialized in different ways.
Variable Declaration
There are two common methods for declaring variables. Suppose we want to declare two int
variables, x
and y
Method 1:
int x; // declare x
int y; // declare y
Method 2
int x, y; // declare x and y
Notice that method 2 works only if x
and y
(and probably more if we want) are of the same type (i.e., int
in this case).
Variable Declaration and Initialization
Method 1:
int x = 10; // declare and initialize x
int y = 20; // declare and initialize y
Method 2:
int x = 10, y = 20; // declare and initialize x and y
Method 3:
int x; // declare x
int y; // declare y
x = 10; // initialize x
y = 20;
Method 4:
int x, y; // declare x and y
x = 10; // initialize x
y = 20; // initialize y
Notice that using the second method, as well as the first method, we may (or may not) initialize the variables we want. For example, if I don't want to initialize y
right I can simply write something like this:
int x = 10, y;
What the professor does in the video, basically, is that he declares two variables (i
and n
) of type int
and initializes them on the same line (see Declaration and Initialization - Method 2). This is definitely a good design tip because after the for
loop ends execution both variablesi
and n
go out of scope (i.e., they're no longer exist). And that's good because we don't really them after the for
loop anymore.
so the following code does work.
for (int i = 0, n = strlen(s); i < n; i++)
{
// do something
}
The problem with your code is that you put a semicolon (i.e., ;
) instead of a comma (i.e., ,
) when you separated the two variables i
and n
. And since the for
loop declaration expects only three sections separated with two semicolons between them as follows
for (declaration and initialization; continuation condition; update)
{
// do something
}
It was confused because you provided 3 semicolons!