Syntax error no for?

Asked

Viewed 75 times

1

Error: (only assignment call increment decrement and new Object Expressions can be used as a statement)

I do not understand why you are giving this error, being that the variable is of type int...

int deQuantidade = 0, ateQuantidade = 0;
string tipo = "";

deQuantidade = Convert.ToInt32(txtDe.Text);
ateQuantidade = Convert.ToInt32(txtAte.Text);
tipo = Convert.ToString(cmbTipo.SelectedIndex);

for (deQuantidade ; deQUantidade < ateQuantidade; deQuantidade++)
{

Error presented:

only assignment call increment decrement and new Object Expressions can be used as a statement

  • 1

    As much as you started the variable above you have to pass value within the for https://docs.microsoft.com/pt-br/dotnet/csharp/language-reference/keywords/for

  • Is there any way to do this with just these variables? Or would you have to actually create another one just to serve as the for initializer?

2 answers

3


First of all... Documentation. Thank you @Krismorte for documentation comment

Understanding what has happened

The error is in the use of for. The for consists of 3 fields (optional): initial assignment, comparison, increment. In the first field, you did not perform any assignment operation, just put the variable name.

This applies in most languages that share the syntax of for traditional C. Some languages have syntax for for-each (other loop expression). Other languages allow the first field to also be declared variable, but C-ANSI89 does not allow.

Yeah, but how to fix it?

Thank you to @Isac for realizing that the value started was reading text, not 0

You could start the value int deQuantidade = Convert.ToInt32(txtDe.Text) in the first field of for:

for (int deQuantidade = Convert.ToInt32(txtDe.Text); deQuantidade < ateQuantidade; deQuantidade++) {
  // ...

This field, by the way, can be used for multiple initializations (comma separated ,):

for (int deQuantidade = Convert.ToInt32(txtDe.Text), int ateQuantidade = Convert.ToInt32(txtAte.Text); deQuantidade < ateQuantidade; deQuantidade++) {
  // ...

Or by keeping the declaration structure before the loop (but not by initializing the variable):

int deQuantidade;
// ...

for (deQuantidade = Convert.ToInt32(txtDe.Text); deQuantidade < ateQuantidade; deQuantidade++) {
  // ...

Or by keeping the boot structure before the loop:

int deQuantidade = 0;
// ...
deQuantidade = Convert.ToInt32(txtDe.Text);
// ...

for (; deQuantidade < ateQuantidade; deQuantidade++) {
  // ...
  • Thank you very much Jefferson ^-^

-2

Try to make the structure of the for that way, because the variable of Quantity within the for becomes a local variable

*

for (deQuantidade = 0; deQuantidade < ateQuantidade; deQuantidade++){
}

*

Browser other questions tagged

You are not signed in. Login or sign up in order to post.