0

Cout and /n

Are this 2 the same thing: cout<<"hello world! \n amazing!" or cout<<"hello world! \n" cout<<"amazing!" ? if not why? sry for the simple question but I've just started learning c++

5th Nov 2018, 1:31 PM
non so
non so - avatar
7 Réponses
+ 4
In output terms, are same.... In coding behaviour context, not... The first sample going transformed to: cout.operator<<("hello world!\namazing"); The second instead: cout.operator<<("hello world!\n"); cout.operator<<("amazing"); This mean that: - In 1) only one string is keep in constant memory, in 2) two string - In 1) only one call to cout.operator<<, in 2) two calls
5th Nov 2018, 1:55 PM
KrOW
KrOW - avatar
+ 3
Yeah it's the same. In second one you just writing first attempt with 2 lines. Edit: in reality for be the same you need to write first one without space between \n and amazing.
5th Nov 2018, 1:47 PM
Anya
Anya - avatar
+ 3
[for KrOW's answer] Here's disassembly showing 3 strings and 3 calls regardless of optimization level: https://godbolt.org/z/2ankHV
5th Nov 2018, 8:05 PM
Kirk Schafer
Kirk Schafer - avatar
+ 3
KrOW I used to have a friend who would make manual optimizations to save bytes (so there'd be pointers to one string, I bet) but I never really got into it. I was hoping to see the compiler figure it out (or some command, same as you) but I couldn't look for very long...I honestly don't know.
5th Nov 2018, 10:08 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Anya I dont think... It would do some optimizations if cout.operator<< method dont handle something with "dynamic" nature like output stream. obliviously internally it can do some optimizations at algorithm level (like use a buffer to be flush at some point) but i dont think that have toi chances to make optimization to low-level code generation level
5th Nov 2018, 3:10 PM
KrOW
KrOW - avatar
+ 1
KrOW this remember me if you don't permit compiler optimizations x+=1 and x=x + 1 is different. x = x + 1 - look x + 1 - copy x in accumulator - add 1 in accumulator - find the place identified by x - copy accumulator result in x x+=1 - find place identified by x - Add 1 in the identified place. But with you let compiler optimize, the compiler will choose the better option depending on situation. p.s. : Couldn't the compiler optimize cout when it's convenient making same effect and result?
5th Nov 2018, 2:38 PM
Anya
Anya - avatar
+ 1
Kirk Schafer Thank you for share that useful service 😉 Anyway, in this case its normal that you have 3 constant strings because you have declared 3 string though seem to me that exist some compilator option that process constabt strings for join they if possible, but maybe i remember wrong 😄
5th Nov 2018, 8:23 PM
KrOW
KrOW - avatar