简体   繁体   中英

<iostream> std:cout within function not printing (FIXED:for loop issue)

NEVERMIND, FIXED IT. for loop issue

I'm trying to do some number crunching with formatted output, and I've run into a problem with half my output not printing. I've written a small test code to illustrate the problem:

#include <iostream>

int testF(){
    for (int i; i<10; i++) {
        std::cout << i << "\n";
    }
    return 0;
}

int main(){
    std::cout << "START_(this_line_seems_to_be_causing_problems)\n";
    int sret = 1;
    sret = testF();
    std::cout << sret << "\n";
    std::cout << "END\n";
    return 0;
}

The problem seems to hinge on the line std::cout << "START_(this_line_seems..." . If I comment out this line, it will print the contents of testF() . If I don't then testF() does not print, although it does give a return value.

It's important that I can print from both main and my functions. Is there a way I can do both?

try initializing i:

int testF(){
for (int i = 0; i<10; i++) {
    std::cout << i << "\n";
}
return 0;
}

and why int sret = 1; // value is never used or passed into function

all you want is:

int sret;
sret = testF();
std::cout << sret << "\n";
std::cout << "END\n";

also why doing

 sret = testF(),

 cout<<sret 

this will just append 0 to your output, instead call testF() directly.

 for (int i; i<10; i++) { 

This loop tries to read from an uninitialised int . That's undefined behaviour , which means everything can happen and that the program may behave strangely.

What probably happens here in practice is that the memory location of the uninitialised variable contains some random data which is interpreted as something greater than 10, and that the random data is somehow affected by the previous std::cout statement. But that's just guessing; the C++ language simply does not define how your program behaves.

In order to avoid undefined behaviour, you must initialise the variable:

for (int i = 0; i<10; i++) {

By the way...

 int sret = 1; sret = testF(); std::cout << sret << "\\n"; 

This can be written more concisely as:

std::cout << testF() << "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM