For loop problem

This is a discussion on For loop problem within the C++ Programming forums, part of the General Programming Boards category; Hello So this code does compile successfully, but outputs nonsense. Code: int f( string str ) { for(int a ; ...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    67

    Smile For loop problem

    Hello

    So this code does compile successfully, but outputs nonsense.

    Code:
    int f( string str )
    {
        for(int a ; a<5 ; a++)
        {
            cout << a;
        }
    }
    
    int main()
    {
        cout << f("a");
        cin.get();
    }
    The output I get is
    2293536

    Shouldn't this normally output the numbers zero through four and return nothing?

    Thanks

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,968
    You failed to initialise a to 0. As for the return value: there is undefined behaviour, since the function does not actually return a value, yet you attempt to use that return value.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    67
    Haha how silly of me.
    Thanks

  4. #4
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Also, the function should be of type void (as you don't return anything), and also does not need to take any argument in this instance.

    It should have been written as such:
    Code:
    void f( )
    {
        for(int a = 0 ; a<5 ; a++)
        {
            cout << a;
        }
    }
    
    int main()
    {
         f();
        cin.get();
    }

  5. #5
    Registered User
    Join Date
    Feb 2010
    Posts
    67
    True, I am aware of the void datatype. The function in my actual program does return a value and takes a string as input. I was just writing an example and didn't bother removing them since I knew the lack of a return value and the string argument weren't the causes of the problem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help understanding a problem
    By dnguyen1022 in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2009, 04:21 PM
  2. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 10:22 AM
  3. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  4. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  5. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM

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