endl or “\n” ?


well this is for c++ programmers.

std::endl and “\n” has just one difference

std::endl calls flush stream but “\n” does not.

Why should i prefer “\n” over endl?

Specially in Loops using “\n” improves performance significantly.

When should i go for std::endl over “\n” ?

#include <iostream>
int main(){
unsigned int i=3;
std::cout<<i<<std::endl;
while(i-=2);
std::cout<<“out Of Loop”;
return 0;
}

This program prints i because endl will flush stream

 

#include <iostream>

int main(){
unsigned int i=3;
std::cout<<i;
while(i-=2);
std::cout<<“out Of Loop”;
return 0;
}

This program does not prints i because no one flushes stream.

It is programmer’s choice whether to use std::endl or “\n” and also depends on program requirement

I would suggest not to use std::endl inside loops, but

if your program contains loops which can lead to infinite loop, then use std::flush before entering loop.

You can use

std::cout<<std::flush;

before entering doubtful loops

 

 

 

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s