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++
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
+ 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.
+ 3
[for KrOW's answer]
Here's disassembly showing 3 strings and 3 calls regardless of optimization level:
https://godbolt.org/z/2ankHV
+ 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.
+ 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
+ 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?
+ 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 😄