Issue with compiling following program

This is a discussion on Issue with compiling following program within the C++ Programming forums, part of the General Programming Boards category; Hi, Following is the program: Code: * Default indent to -1. This value tells the function to reuse the previous ...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    139

    Issue with compiling following program

    Hi,

    Following is the program:

    Code:
    * Default indent to -1. This value tells the function
    to reuse the previous value. */
    void iputs(char *str, int indent = -1);
    int main()
    {
    iputs("Hello there", 10);
    iputs("This will be indented 10 spaces by default");
    iputs("This will be indented 5 spaces", 5);
    iputs("This is not indented", 0);
    return 0;
    }
    void iputs(char *str, int indent)
    {
    //Statement 1
    static i = 0; // holds previous indent value //followin line is throwing error
    if(indent >= 0)
    i = indent;
    else // reuse old indent value
    indent = i;
    for( ; indent; indent--) cout << " ";
    cout << str << "\n";
    }
    1. What does statement 1 mean?
    2. How does this program achieve the concept of default argument?
    3. It throws compiler error at the above statement 1.

    Thanks in advance

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,454
    To answer questions 1 and 3, "Statement 1" is presumably declaring a static variable named i that is local to the iputs(). It is invalid (hence the compiler complains) as the statement does not specify a type for i. Assuming it is meant to be int, the statement should be "static int i = 0;"

    static, in this case, means the value of i is saved between calls of the function.

    To answer your second question, look at the declaration of iputs() near the top of your code
    Code:
    void iputs(char *str, int indent = -1);
    The bit I've highlighted in red specifies a default value for the argument (indent) of -1. This means that when calling the function, if the second argument is not provided, a value of -1 is supplied.
    Right 98% of the time, and don't care about the other 3%.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C compiling / error: stray \ in program
    By Elya in forum C Programming
    Replies: 5
    Last Post: 07-02-2009, 08:20 AM
  2. Help Needed with Compiling C program
    By girishaneja in forum C Programming
    Replies: 2
    Last Post: 05-20-2009, 08:10 AM
  3. Issue with program that's calling a function and has a loop
    By tigerfansince84 in forum C++ Programming
    Replies: 9
    Last Post: 11-12-2008, 12:38 PM
  4. beginning C Programmer - Need Help Compiling Program
    By fisguts in forum C Programming
    Replies: 2
    Last Post: 07-30-2008, 02:14 PM
  5. Replies: 4
    Last Post: 03-10-2008, 07:03 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21