5

I just tried compiling some C++ code that used the literal Tab character (as in I pressed the TAB key on my keyboard) inside a string. And, to my surprise, it compiled fine. In retrospect I guess that makes sense, since it's a character just like any other.

cout << "Tab: [TAB]";

Before now I've always used \t to define tabs in strings.

cout << "Tab: [\t]";

Obviously code using literal TABs in strings would suffer greatly in readability, but is there a technical reason to use \t other than convention?

TheSchwa
  • 853
  • 10
  • 19
  • It's unclear what you're asking. Do you have code that demonstrates the functionality you're trying to achieve or highlights an issue you were having? – Xirema Feb 22 '16 at 22:16
  • 1
    @Xirema I'm not sure how to be more clear about it...why should I use `"\t"` in a C++ string rather than literally pressing the `TAB` key on my keyboard. The functionality appears to be the same either way. So why is one better than the other? – TheSchwa Feb 22 '16 at 22:18
  • 4
    @Xirema It's clear enough. – πάντα ῥεῖ Feb 22 '16 at 22:19
  • 8
    Many developers have editor settings which automatically convert tabs into spaces. If you used literal tabs, they would get converted into spaces which is probably undesirable. – merlin2011 Feb 22 '16 at 22:19
  • For one thing, you can tell the difference between \t and a bunch of spaces. – user253751 Feb 22 '16 at 22:24

1 Answers1

9

but is there a technical reason to use \t other than convention?

Sure there are technical reasonings. Using

cout << "Tab: [\t]";

would work independently of the target systems actual character encoding.

The source file could use a different encoding as the target system does, e.g. UTF8 for source, but EBCDIC at the target system.
'\t' will always be translated to the correct character code though, thus the code is portable.


Also as mentioned in merlin2011's comment many IDE's will just replace TAB with a specific number of spaces.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190