
@c This is part of The GNU C Reference Manual
@c Copyright (C) 2003, 2004, 2006-2009 Free Software Foundation, Inc.
@c See the file gnu-c-manual.texi for copying conditions.

@node Statements
@chapter Statements
@cindex statements

You write statements to cause actions and to control flow within your
programs.  You can also write statements that do not do anything at all,
or do things that are uselessly trivial.

@menu
* Labels::
* Expression Statements::       
* The if Statement::     
* The switch Statement::  
* The while Statement::  
* The do Statement::     
* The for Statement::    
* Blocks::                      
* The Null Statement::          
* The goto Statement::   
* The break Statement::  
* The continue Statement::  
* The return Statement::  
* The typedef Statement::
@end menu

@node Labels
@section Labels
@cindex labels
@cindex labeled statements
@cindex statements, labeled

You can use labels to identify a section of source code for use with a
later @code{goto} (@pxref{The goto Statement}).  A label consists of an
identifier (such as those used for variable names) followed by a
colon.  Here is an example:

@example
@group
treet:
@end group
@end example

You should be aware that label names do not interfere with other
identifier names:

@example
@group
int treet = 5;    /* @r{@code{treet} the variable.} */
treet:            /* @r{@code{treet} the label.} */
@end group
@end example

The ISO C standard mandates that a label must be followed by at least
one statement, possibly a null statement (@pxref{The Null Statement}).
GCC will compile code that does not meet this requirement, but be
aware that if you violate it, your code may have portability issues.


@node Expression Statements
@section Expression Statements
@cindex expression statements
@cindex statements, expression

You can turn any expression into a statement by adding a semicolon to
the end of the expression.  Here are some examples:

@example
@group
5;
2 + 2;
10 >= 9;
@end group
@end example

In each of those, all that happens is that each expression is
evaluated.  However, they are useless because they do not store
a value anywhere, nor do they actually do anything, other than
the evaluation itself.  The compiler is free to ignore such
statements.

Expression statements are only useful when they have some kind
of side effect, such as storing a value, calling a function, or
(this is esoteric) causing a fault in the program.  Here are
some more useful examples:

@example
@group
x++;
y = x + 25;
puts ("Hello, user!");
*cucumber;
@end group
@end example

The last of those statements, @code{*cucumber;}, could potentially
cause a fault in the program if the value of @code{cucumber} is both
not a valid pointer and has been declared as @code{volatile}.

@comment reference to `volatile'


@node The if Statement
@section The @code{if} Statement
@cindex @code{if} statements
@cindex @code{else} statements

You can use the @code{if} statement to conditionally execute part of your
program, based on the truth value of a given expression.  Here is the
general form of an @code{if} statement:

@example
@group
if (@var{test})
  @var{then-statement}
else
  @var{else-statement}
@end group
@end example

If @var{test} evaluates to true, then @var{then-statement} is executed and
@var{else-statement} is not.  If @var{test} evaluates to false, then
@var{else-statement} is executed and @var{then-statement} is not.  The
@code{else} clause is optional.

Here is an actual example:

@example
@group
if (x == 10)
  puts ("x is 10");
@end group
@end example

If @code{x == 10} evaluates to true, then the statement
@code{puts ("x is 10");} is executed.  If @code{x == 10} evaluates to
false, then the statement @code{puts ("x is 10");} is not executed.

Here is an example using @code{else}:

@example
@group
if (x == 10)
  puts ("x is 10");
else
  puts ("x is not 10");
@end group
@end example

You can use a series of @code{if} statements to test for multiple
conditions:

@example
@group
if (x == 1)
  puts ("x is 1");
else if (x == 2)
  puts ("x is 2");
else if (x == 3)
  puts ("x is 3");
else
  puts ("x is something else");
@end group
@end example

This function calculates and displays the date of Easter for the given year @code{y}:

@example
void
easterDate (int y)
@{
  int n = 0;
  int g = (y % 19) + 1;
  int c = (y / 100) + 1;
  int x = ((3 * c) / 4) - 12;
  int z = (((8 * c) + 5) / 25) - 5;
  int d = ((5 * y) / 4) - x - 10;
  int e = ((11 * g) + 20 + z - x) % 30;

  if (((e == 25) && (g > 11)) || (e == 24))
    e++;

  n = 44 - e;

  if (n < 21)
    n += 30;

  n = n + 7 - ((d + n) % 7);

  if (n > 31)
    printf ("Easter: %d April %d", n - 31, y);
  else
    printf ("Easter: %d March %d", n, y);
@}
@end example

@node The switch Statement
@section The @code{switch} Statement
@cindex @code{switch} statement

You can use the @code{switch} statement to compare one expression with others,
and then execute a series of sub-statements based on the result of the
comparisons.  Here is the general form of a @code{switch} statement:

@example
@group
switch (@var{test})
  @{
    case @var{compare-1}:
      @var{if-equal-statement-1}
    case @var{compare-2}:
      @var{if-equal-statement-2}
    @dots{}
    default:
      @var{default-statement}
  @}
@end group
@end example

The @code{switch} statement compares @var{test} to each of the
@var{compare} expressions, until it finds one that is
equal to @var{test}.  Then, the statements following the successful
case are executed.  All of the expressions compared must be of an integer
type, and the @var{compare-N} expressions must be of a constant integer
type (e.g., a literal integer or an expression built of literal integers).

Optionally, you can specify a default case.  If @var{test} doesn't match
any of the specific cases listed prior to the default case, then
the statements for the default case are executed.  Traditionally, the
default case is put after the specific cases, but that isn't required.


@example
@group
switch (x)
  @{
    case 0:
      puts ("x is 0");
      break;
    case 1:
      puts ("x is 1");
      break;
    default:
      puts ("x is something else");
      break;
  @}
@end group
@end example

Notice the usage of the @code{break} statement in each of the cases.  This
is because, once a matching case is found, not only are its statements
executed, but so are the statements for all following cases:

@example
@group
int x = 0;
switch (x)
  @{
    case 0:
      puts ("x is 0");
    case 1:
      puts ("x is 1");
    default:
      puts ("x is something else");
  @}
@end group
@end example

@noindent
The output of that example is:

@example
@group
x is 0
x is 1
x is something else
@end group
@end example

This is often not desired.  Including a @code{break} statement at the
end of each case redirects program flow to after the @code{switch} statement.

As a GNU C extension, you can also specify a range of consecutive integer
values in a single @code{case} label, like this:

@example
case @var{low} ... @var{high}:
@end example

@noindent
This has the same effect as the corresponding number of individual @code{case}
labels, one for each integer value from @var{low} to @var{high}, inclusive.

This feature is especially useful for ranges of ASCII character codes:

@example
case 'A' ... 'Z':
@end example

Be careful to include spaces around the @code{...}; otherwise it
may be parsed incorrectly when you use it with integer values.  For
example, write this:

@example
case 1 ... 5:
@end example

@noindent
instead of this:

@example
case 1...5:
@end example

It is common to use a @code{switch} statement to handle various
possible values of @code{errno}.  In this case a portable program
should watch out for the possibility that two macros for @code{errno}
values in fact have the same value, for example @code{EWOULDBLOCK} and
@code{EAGAIN}.


@node The while Statement
@section The @code{while} Statement
@cindex @code{while} statement

The @code{while} statement is a loop statement with an exit test at
the beginning of the loop.  Here is the general form of the @code{while}
statement:

@example
@group
while (@var{test})
  @var{statement}
@end group
@end example

The @code{while} statement first evaluates @var{test}.  If @var{test}
evaluates to true, @var{statement} is executed, and then @var{test} is
evaluated again.  @var{statement} continues to execute repeatedly as long as
@var{test} is true after each execution of @var{statement}.  

This example prints the integers from zero through nine:

@example
@group
int counter = 0;
while (counter < 10)
  printf ("%d ", counter++);
@end group
@end example

A @code{break} statement can also cause a @code{while} loop to exit.

@node The do Statement
@section The @code{do} Statement
@cindex @code{do} statement

The @code{do} statement is a loop statement with an exit test at the end
of the loop.  Here is the general form of the @code{do} statement:

@example
@group
do
  @var{statement}
while (@var{test});
@end group
@end example

The @code{do} statement first executes @var{statement}.  After that,
it evaluates @var{test}.  If @var{test} is true, then @var{statement} is
executed again.  @var{statement} continues to execute repeatedly as long as
@var{test} is true after each execution of @var{statement}.

This example also prints the integers from zero through nine:

@example
@group
int x = 0;
do
  printf ("%d ", x++);
while (x < 10);
@end group
@end example

A @code{break} statement can also cause a @code{do} loop to exit.

@node The for Statement
@section The @code{for} Statement
@cindex @code{for} statement

The @code{for} statement is a loop statement whose structure allows
easy variable initialization, expression testing, and variable
modification.  It is very convenient for making counter-controlled
loops.  Here is the general form of the @code{for} statement:

@example
for (@var{initialize}; @var{test}; @var{step})
  @var{statement}
@end example

The @code{for} statement first evaluates the expression @var{initialize}.
Then it evaluates the expression @var{test}.  If @var{test} is false, then
the loop ends and program control resumes after @var{statement}.  Otherwise,
if @var{test} is true, then @var{statement} is executed.  Finally,
@var{step} is evaluated, and the next iteration of the loop begins with
evaluating @var{test} again.

Most often, @var{initialize} assigns values to one or more variables,
which are generally used as counters,  @var{test} compares those
variables to a predefined expression, and @var{step} modifies those
variables' values.  Here is another example that prints the integers
from zero through nine:

@example
@group
int x;
for (x = 0; x < 10; x++)
  printf ("%d ", x);
@end group
@end example

First, it evaluates @var{initialize}, which assigns @code{x} the value
0.  Then, as long as @code{x} is less than 10, the value of @code{x}
is printed (in the body of the loop).  Then @code{x} is incremented in
the @var{step} clause and the test re-evaluated.

All three of the expressions in a @code{for} statement are optional, and any
combination of the three is valid.  Since the first expression is evaluated
only once, it is perhaps the most commonly omitted expression.  You could
also write the above example as:

@example
@group
int x = 1;
for (; x <= 10; x++)
  printf ("%d ", x);
@end group
@end example

@noindent
In this example, @code{x} receives its value prior to the beginning of the
@code{for} statement.

If you leave out the @var{test} expression, then the @code{for} statement
is an infinite loop (unless you put a @code{break} or @code{goto} statement
somewhere in @var{statement}).  This is like using @code{1} as
@var{test}; it is never false.

This @code{for} statement starts printing numbers at 1 and then
continues indefinitely, always printing @code{x} incremented by 1:

@example
@group
for (x = 1; ; x++)
  printf ("%d ", x);
@end group
@end example

If you leave out the @var{step} expression, then no progress is made
toward completing the loop---at least not as is normally expected with
a @code{for} statement.

This example prints the number 1 over and over, indefinitely:

@example
@group
for (x = 1; x <= 10;)
  printf ("%d ", x);
@end group
@end example

Perhaps confusingly, you cannot use the comma operator (@pxref{The
Comma Operator}) for monitoring multiple variables in a @code{for}
statement, because as usual the comma operator discards the result of
its left operand.  This loop:

@example
@group
int x, y;
for (x = 1, y = 10; x <= 10, y >= 1; x+=2, y--)
  printf ("%d %d\n", x, y);
@end group
@end example

@noindent Outputs:

@example
1 10
3 9
5 8
7 7
9 6
11 5
13 4
15 3
17 2
19 1
@end example

If you need to test two conditions, you will need to use the @code{&&}
operator:

@example
@group
int x, y;
for (x = 1, y = 10; x <= 10 && y >= 1; x+=2, y--)
  printf ("%d %d\n", x, y);
@end group
@end example

A @code{break} statement can also cause a @code{for} loop to exit.

Here is an example of a function that computes the summation of squares, given a 
starting integer to square and an ending integer to square:

@example
@group
int
sum_of_squares (int start, int end)
@{
  int i, sum = 0;
  for (i = start; i <= end; i++)
    sum += i * i;
  return sum;
@}
@end group
@end example

@node Blocks
@section Blocks
@cindex blocks
@cindex compound statements

A @dfn{block} is a set of zero or more statements enclosed in braces.
Blocks are also known as @dfn{compound statements}.  Often, a block is
used as the body of an @code{if} statement or a loop statement, to
group statements together.

@example
@group
for (x = 1; x <= 10; x++)
  @{
    printf ("x is %d\n", x);
    
    if ((x % 2) == 0)
      printf ("%d is even\n", x);
    else
      printf ("%d is odd\n", x);
  @}
@end group
@end example

You can also put blocks inside other blocks:

@example
@group
for (x = 1; x <= 10; x++)
  @{
    if ((x % 2) == 0)
      @{
        printf ("x is %d\n", x);
        printf ("%d is even\n", x);
      @}
    else
      @{
        printf ("x is %d\n", x);
        printf ("%d is odd\n", x);
      @}
  @}
@end group
@end example  

You can declare variables inside a block; such variables are local to
that block.  In C89, declarations must occur before other statements,
and so sometimes it is useful to introduce a block simply for this
purpose:

@comment scope reference  (locality)

@example
@group
@{
  int x = 5;
  printf ("%d\n", x);
@}
printf ("%d\n", x);   /* @r{Compilation error! @code{x} exists only}
                       @r{in the preceding block.} */
@end group
@end example


@node The Null Statement
@section The Null Statement
@cindex null statement
@cindex statement, null

The @dfn{null statement} is merely a semicolon alone.

@example
@group
;
@end group
@end example

A null statement does not do anything.  It does not store a value anywhere.
It does not cause time to pass during the execution of your program.

Most often, a null statement is used as the body of
a loop statement, or as one or more of the expressions in a @code{for}
statement.  Here is an example of a @code{for} statement that uses the
null statement as the body of the loop (and also calculates the integer
square root of @code{n}, just for fun):

@example
@group
for (i = 1; i*i < n; i++)
  ;
@end group
@end example

Here is another example that uses the null statement as the body
of a @code{for} loop and also produces output:

@example
@group
for (x = 1; x <= 5; printf ("x is now %d\n", x), x++)
  ;
@end group
@end example

A null statement is also sometimes used to follow a label that would
otherwise be the last thing in a block.


@node The goto Statement
@section The @code{goto} Statement
@cindex @code{goto} statement

You can use the @code{goto} statement to unconditionally jump to a different
place in the program.  Here is the general form of a @code{goto} statement:

@example
goto @var{label};
@end example

You have to specify a label to jump to; when the @code{goto} statement
is executed, program control jumps to that label.  @xref{Labels}.  Here
is an example:

@example
@group
goto end_of_program;
@dots{}
end_of_program:
@end group
@end example

The label can be anywhere in the same function as the @code{goto}
statement that jumps to it, but a @code{goto} statement cannot jump to a
label in a different function.

You @emph{can} use @code{goto} statements to simulate loop statements,
but we do not recommend it---it makes the program harder to read, and GCC
cannot optimize it as well.  You should use @code{for},
@code{while}, and @code{do} statements instead of @code{goto} statements,
when possible.

As an extension, GCC allows a goto statement to jump to an address
specified by a @code{void*} variable.  To make this work, you also
need to take the address of a label by using the unary operator
@code{&&} (not @code{&}).  Here is a contrived example:

@example
@group
enum Play @{ ROCK=0, PAPER=1, SCISSORS=2 @};
enum Result @{ WIN, LOSE, DRAW @};

static enum Result turn (void) 
@{
  const void * const jumptable[] = @{&&rock, &&paper, &&scissors@};
  enum Play opp;                /* @r{opponent's play} */
  goto *jumptable[select_option (&opp)];
 rock:
  return opp == ROCK ? DRAW : (opp == PAPER ? LOSE : WIN);
 paper:
  return opp == ROCK ? WIN  : (opp == PAPER ? DRAW : LOSE);
 scissors:
  return opp == ROCK ? LOSE : (opp == PAPER ? WIN  : DRAW);
@}
@end group
@end example

@c Here we should mention that programs should not jump over an
@c initializer with a goto (and elsewhere say the same for a case
@c label).  However, just now I can't find the section of the C89
@c standard that stipulates this.


@node The break Statement
@section The @code{break} Statement
@cindex @code{break} statement

You can use the @code{break} statement to terminate a @code{while}, @code{do},
@code{for}, or @code{switch} statement.  Here is an example:

@example
@group
int x;
for (x = 1; x <= 10; x++)
  @{
    if (x == 8)
      break;
    else
      printf ("%d ", x);
  @}
@end group
@end example

That example prints numbers from 1 to 7.  When @code{x} is incremented
to 8, @code{x == 8} is true, so the @code{break} statement is executed, 
terminating the @code{for} loop prematurely.

If you put a @code{break} statement inside of a loop or @code{switch}
statement which itself is inside of a loop or @code{switch} statement, the
@code{break} only terminates the innermost loop or @code{switch} statement.


@node The continue Statement
@section The @code{continue} Statement
@cindex @code{continue} statement

You can use the @code{continue} statement in loops to terminate an
iteration of the loop and begin the next iteration.  Here is an
example:

@example
@group
for (x = 0; x < 100; x++)
  @{
    if (x % 2 == 0)
      continue;
    else
      sum_of_odd_numbers + = x;
  @}
@end group
@end example

If you put a @code{continue} statement inside a loop which itself is
inside a loop, then it affects only the innermost loop.



@node The return Statement
@section The @code{return} Statement
@cindex @code{return} statement

You can use the @code{return} statement to end the execution of a function
and return program control to the function that called it.  Here is the
general form of the @code{return} statement:

@example
return @var{return-value};
@end example

@var{return-value} is an optional expression to return.  If the
function's return type is @code{void}, then it is invalid to return
an expression.  You can, however, use the @code{return} statement
without a return value.

If the function's return type is not the same as the type of
@var{return-value}, and automatic type conversion cannot be performed,
then returning @var{return-value} is invalid.

@comment Reference to type conversion

If the function's return type is not @code{void} and no return value
is specified, then the @code{return} statement is valid unless the
function is called in a context that requires a return value.  For
example:

@example
x = cosine (y);
@end example

In that case, the function @code{cosine} was called in a context that
required a return value, so the value could be assigned to @code{x}.

Even in contexts where a return value is not required, it is a bad idea
for a non-@code{void} function to omit the return value.  With GCC, you
can use the command line option @code{@w{-Wreturn}-type} to issue a warning
if you omit the return value in such functions.

Here are some examples of using the @code{return} statement, in both
a @code{void} and non-@code{void} function:

@example
@group
void
print_plus_five (int x)
@{
  printf ("%d ", x + 5);
  return;
@}
@end group
@end example

@example
@group
int
square_value (int x)
@{
  return x * x;
@}
@end group
@end example


@node The typedef Statement
@section The @code{typedef} Statement
@cindex @code{typedef} statement

You can use the @code{typedef} statement to create new names for data
types.  Here is the general form of the @code{typedef} statement:

@example
typedef @var{old-type-name} @var{new-type-name}
@end example

@var{old-type-name} is the existing name for the type, and may consist
of more than one token (e.g., @code{unsigned long int}).
@var{new-type-name} is the resulting new name for the type, and must
be a single identifier.  Creating this new name for the type does
not cause the old name to cease to exist.  Here are some examples:

@example
@group
typedef unsigned char byte_type;
typedef double real_number_type;
@end group
@end example

@noindent
In the case of custom data types, you can use @code{typedef} to make a
new name for the type while defining the type:

@example
@group
typedef struct fish
@{
  float weight;
  float length;
  float probability_of_being_caught;
@} fish_type;
@end group
@end example

@noindent
To make a type definition of an array, you first provide the type of the element, and
then establish the number of elements at the end of the type definition:

@example
@group
typedef char array_of_bytes [5];
array_of_bytes five_bytes = @{0, 1, 2, 3, 4@};
@end group
@end example

When selecting names for types, you should avoid ending your type names with
a @code{_t} suffix.  The compiler will allow you to do this, but the
POSIX standard reserves use of the @code{_t} suffix for standard library
type names.
