Is there a difference between;
int main(){
return 0;
}
and
int main(){return 0;}
and
int main(){
return
0;
}
They will all likely compile to same executable. How does the C/C compiler treat the extra spaces and newlines, and if there is a difference between how newlines are treated differently than spaces in C code?
Also, how about tabs? What's the significance of using tabs instead of spaces in code, if there is any?
CodePudding user response:
Any sequence of 1 whitespace symbol (space/line-break/tab/...) is equivalent to a single space.
Exceptions:
- Whitespace is preserved in string literals. They can't contain line-breaks, except C raw literals (
R"(...)"
). The same applies to file names in#include
. - Single-line comments (
//
) are terminated with line-breaks only. - Preprocessor directives (starting with
#
) are terminated with line-breaks only. \
followed by a line-break removes both, allowing multi-line//
comments, preprocessor directrives, and string literals.
Also, whitespace symbols are ignored if there is punctuation (anything except letters, numbers, and _
) to the left and/or to the right of it. E.g. 1 2
and 1 2
are the same, but return a;
and returna;
are not.
Exceptions:
Whitespace is not ignored inside string literals, obviously. Nor in
#include
file names.Operators consisting of >1 punctuation symbols can't be separated, e.g.
cout < < 1
is illegal. The same applies to things like//
and/*
*/
.A space between punctuation might be necessary to prevent it from coalescing into a single operator. Examples:
a
is different froma
.a b
is equivalent toa b
, but not toa b
.- Pre-C 11, closing two template argument lists in a row required a space:
std::vector<std::vector<int> >
.
When defining a function-like macro, the space is not allowed before the opening parenthesis (adding it turns it into an object-like macro). E.g.
#define A()
replacesA()
with nothing, but#define A ()
replacesA
with()
.