0

I try to understand this code but I don't know how this part work:

for (length = 0; t[length]; length++);
length--;

And specially I want to know how this for (length = 0; t[length]; length++); work?! what does for(); mean? what does this ; (semicolon) mean that comes after for() in c code instead of {}?

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main() {
    char t[] = "abcdefghijklmnopqrstuvwxyz", temp;
    int i, length;
    system("cls");
    for (length = 0; t[length]; length++);
        length--;
    puts("the initial text is :");
    puts(t);
    for (i = 0; i < length / 2; i++) {
        temp = t[i];
        t[i] = t[length - i];
        t[length - i] = temp;
    }
    puts("the reversd test is :");
    puts(t);
    getch();
    return 0;
}

I pleased if someone help me and explain about that part of this code... what for(); mean??

  • 3
    `for (length = 0; t[length]; length++);` means the same as `for (length = 0; t[length]; length++) {}`. Its purpose is to increment `length` until `t[length]` is `0`. Then the next line makes an adjustment to `length.` – Weather Vane Oct 20 '20 at 15:44
  • `length--;` should not be indented in your code. – stark Oct 20 '20 at 16:48
  • @Mohammad Razmjoo This means just a bad code that has a bug and nothing more.:) – Vlad from Moscow Oct 20 '20 at 17:10

3 Answers3

2

The body of a for loop can be any statement. That includes a compound statement:

for(...) {
   do_something;
}

Or a single statement:

for(...) do_something;

One of the types of statements is a null statement, which is just ;. So this:

for (length = 0; t[length]; length++);

Is a loop whose body is the null statement ;. It's the same as:

for (length = 0; t[length]; length++) {
}
dbush
  • 205,898
  • 23
  • 218
  • 273
0

a for loop consists of an initialization/assignment length = 0; condition t[length]; and iteration length++ if a for loop has only one line you don't need thee curly brackets to open and close it. so if you don't want to have anything inside your for loop and just get your variable to a certain condition you can use it like that and put a semi colon after the for loop.

Gilad
  • 305
  • 1
  • 2
  • 8
0

length will keep being incremented as long as t[length] does not evaluate to 0 or FALSE. length is then decremented and is the index of the last element in the array t.

Tarik
  • 10,810
  • 2
  • 26
  • 40