Whitespaces

This page was translated by a robot.

In the languages ​​C and C++, blanks such as space, tabulator and line break have no semantic meaning but only serve to separate syntactical elements. Such spaces are called whitespaces . For example, while other languages ​​such as BASIC treat the newline as a delimiter between statements, C and C++ do not use newlines, which allow multiple statements to be written on one line::




8

In C and C++, all trailing blanks are interpreted as a single separator at compile time. This separates the individual elements, but does not interrupt the statements. So even the following statements are equivalent to the statements above:

#include <stdio.h>

int main(){
  int       a =
     5  ;       int
b=3          ;    int
  c=     a +
   b;    printf   ("%d\n"
      ,c);
  return            0;
}

The only question that arises here is readability. It should be noted that spaces, although combined into a single space, still have a delimiting character. If you try to split a symbol or keyword with spaces, the compiler interprets this as two elements. The following lines of code are therefore NOT equivalent to the code above and lead to errors:




error
#include <stdio.h>

int main(){
  i n t a = 5;
  i nt b = 3;
  in    t c = a + b;
  pr in tf("%d\n",  c);
  re t urn 0;
}

Using spaces, the programmer can write his code in a visually supporting form, which is also supported by modern programming environments. The most important visual element is the indentation of lines within a code block, which is referred to as indentation .



0, 0
1, 0
2, 0
0, 1
1, 1
2, 1
0, 2
1, 2
2, 2
#include <stdio.h>

int main(){
  int x, y;
  for(y=0; y<3; y++){
    for(x=0; x<3; x++){
      printf("%d, %d\n",  x, y);
    }
  }
  return 0;
}

Many sources recommend putting only one statement on each line. The recommendation on this page is to group related, easy-to-understand statements together, pack longer statements in one line, and spread particularly long statements over several lines for legibility.

x=a[0]; y=a[1]; z=a[2];

sendMessage(windowref, "Alert!", "Ok", "Cancel", true);

return Matrix22(a[0]*m2.a[0] + a[1]*m2.a[2],
                a[0]*m2.a[1] + a[1]*m2.a[3],
                a[2]*m2.a[0] + a[3]*m2.a[2],
                a[2]*m2.a[1] + a[3]*m2.a[3]);
Next Chapter: Comments // /* */