Solved

for statement question

Posted on 2006-10-21
13
285 Views
Last Modified: 2010-04-15
Hi,
could someone explain the following code for me (I don't get the line with ? mark) thank you very much!

   #include <stdio.h>
   #define MAXLINE 1000   /* maximum input line length */

   int getline(char line[], int maxline);
   void copy(char to[], char from[]);

   /* print the longest input line */
   main()
   {
       int len;            /* current line length */
       int max;            /* maximum length seen so far */
       char line[MAXLINE];    /* current input line */
       char longest[MAXLINE]; /* longest line saved here */

       max = 0;
       while ((len = getline(line, MAXLINE)) > 0)
           if (len > max) {
               max = len;
               copy(longest, line);
           }
       if (max > 0)  /* there was a line */
           printf("%s", longest);
       return 0;
   }



 /* getline:  read a line into s, return length  */
   int getline(char s[],int lim)
   {
       int c, i;

       for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)  --------------------------------------------?
           s[i] = c;
       if (c == '\n') {
           s[i] = c;
           ++i;
       }
       s[i] = '\0';
       return i;
   }
0
Comment
Question by:rmtogether
  • 5
  • 3
  • 3
  • +1
13 Comments
 
LVL 30

Assisted Solution

by:callrs
callrs earned 100 total points
ID: 17781577
 for (i=0;
 -> start loop with i=0

i < lim-1 && (c=getchar())!=EOF && c!='\n';

-> continue while:
- i is less than lim-1 AND
- (get a byte, assign the byte to c)
- c is not end-of-file AND
- c is not end-of-line

 ++i)
-> Increment i by one with each iteration of the loop
0
 
LVL 30

Expert Comment

by:callrs
ID: 17781593
http://www.sysprog.net/cloop.html    C loops

for (INITIALIZATION; CONDITION; ITERATION)
   {
   BODY
   }
0
 
LVL 30

Expert Comment

by:callrs
ID: 17781665
\n means newline:
"The C programming language provides the escape sequences '\n' (newline) and '\r' (carriage return). " (http://en.wikipedia.org/wiki/CRLF)
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 

Author Comment

by:rmtogether
ID: 17781707
why use lim-1 ? why not just use lim?
0
 
LVL 30

Expert Comment

by:callrs
ID: 17781789
Arrays of course start at 0 index, not 1, so s[0] would hold the first byte etc., but that doesn't seem to be a factor in this case

lim shoud work too. You can try it & test it with MAXLINE set to a lower number like 50

I think it uses lim-1 to save a step: Since you don't need to read in the newline character, just skip it.

0
 
LVL 16

Assisted Solution

by:PaulCaswell
PaulCaswell earned 50 total points
ID: 17782008
Hi rmtogether,

It's lim-1 because you are building a string so you need to leave room for the null terminator on the end.

       s[i] = '\0';

If it was i<lim then at the end of the loop i will be == lim so this line will write beyond the limit specified.

Paul
0
 

Author Comment

by:rmtogether
ID: 17782143
hi,
in the for statement has c!='\n', but insie brace has c=='\n'. I am confused about this.?
0
 
LVL 16

Expert Comment

by:PaulCaswell
ID: 17782182
The loop walks through the line and stops either when the character it is looking at is a return or it hits the end of the file.

The check for c=='n' is just making sure it doesnt add the character if end of file is reached.

Paul
0
 
LVL 30

Expert Comment

by:callrs
ID: 17782191
!=      -> not equals
so: continue loop if c is not equal to '\n'

==      -> equals
so: run the 'if' block only if the current byte is a '\n'

So, it seems that the if block will never get executed, and so the if block is superfluous...
Change of code: If you want to include the newline character in s, then remove the c!='\n' condition; else remove the if block.

I'll leave it for Paul to verify or correct my hunch.  [Thanks Paul about the '\0'. I forgot to read beyond the loop.]
0
 
LVL 45

Accepted Solution

by:
sunnycoder earned 100 total points
ID: 17782349
>in the for statement has c!='\n', but insie brace has c=='\n'. I am confused about this.?
The != check is the for loop and == check is outside the for loop ...

The for loop can temrinate on one of these conditions
a) EOF was read
b) Newline was read

In case newline (\n) was read then at the end of loop, array line will NOT contain \n, and c will contain \n.

The check AFTER for loop " if (c == '\n')" checks if this was the case ... If yes, then it adds newline to buffer. This is similar in behavior to fgets that reads in newline too.

However, there is a potential bug in the program ... It loops to lim, i.e. it has valid locations from 0 to lim-1 .. In the for loop it fills up all locations from 0 to lim -2 (loop says < l-1) and after loop it potentially adds two characters (\n and \0) while it has memory for only one.

This is a buffer overrun and can cause crash/corruption
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 17782352
The for loop can temrinate on one of these conditions
a) EOF was read
b) Newline was read
or lim-2 characters were read ... Very important but not significant for demonstrating why the if statement is there
0
 

Author Comment

by:rmtogether
ID: 17782467

What is the purpose of the getline function.
Is it used for return the length of each line of a input file?
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 17782473
Yes, that is what the function is being used for ...

Purpose of getline
 /* getline:  read a line into s, return length  */
0

Featured Post

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Dll Dynamic way c/c++ 9 145
how to declare a 2-dimensional version of strlen 4 209
Passing a array as parameter - C 2 95
How to learn Linux? 10 61
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question