Is it “bad practice” to use tab characters in string literals?

泄露秘密 提交于 2019-12-01 23:50:20

问题


As a follow-up on Is it mandatory to escape tabulator characters in C and C++? (do note I'm not the author of said question).

I've learned such code is considered "bad practice". The comments seem to be suggesting the same thing. However, for some reason the standard allows this trickery so somebody must either found no harm in it or has a use-case for it.

Is not escaping tabulator characters widely accepted as "bad practice"?


回答1:


Using tabs in litterals instead of escaping them ('\t',"\t") is a bad practice because :

  • the reader is not immediately aware that there is a tab. Consequence: wrong assumptions about code, wrong changes (for example when allignemnt of code output needs to be adapted)
  • the tab expansion might be different depending on your editor. Consequence: hindering of teamwork and maintenance, as different people may see different layouts.
  • MOST OF ALL: some editors convert tabs to spaces when saving your source file (using the configured tab expansion settings) getting rid of such embedded tabs. Consequence: unnoticed/undesired change (f.ex: when a teammember uses such an editor and make a minor edit, not even in this string).



回答2:


I've never really thought about it, but I can't imagine finding literal tabspace characters a good idea because you cannot immediately distinguish them from standard whitespace. If you need a tabspace in your string literal for some specific reason, it's more clear and explicit to write \t so that everybody knows precisely what you intended to do.

By the way, the notion that there must be a good use case just because the standard allows it … is somewhat broken. For example, the standard allows us to declare raw pointers, and to write new.



来源:https://stackoverflow.com/questions/28917023/is-it-bad-practice-to-use-tab-characters-in-string-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!