A statement is something that a program does for its effect. Unlike an expression, a statement does not have an answer.
Add a semicolon to the end of an expression and it becomes a statement. For example, x+1 is an expression, so x+1; is a statement. If E is an expression, then statement E; computes the value of E and ignores the answer. That means
x+1;has no effect. It computes the value of x+1 and ignores the answer.
Be careful about that. There is a big difference between
x = x + 1;and
x+1;
A function call is an expression. Add a semicolon and it becomes a statement. Statement
scanf("%i", &y);is a call to function scanf, made into a statement. Recall that scanf returns an integer, the number of values that were successfully read. That integer is being ignored.
Watch out for this. Most of the time, if a function returns an answer, you need to use the answer. Only ignore an answer if you are sure that you can afford to ignore it.
Some functions, such as printf, have no answer, so you are required to use them as statements. To define a function that has no answer, write void for its return type. For example, after defining
void SayHello() { printf("Hello\n"); }statement
SayHello();prints Hello, followed by a newline.
Each call to a function runs the function. Statements
SayHello(); SayHello();write
Hello HelloSome students get an incorrect mental model of how to call a function, and write something like the following.
sqrt(x); y = sqrt(x);where the student imagines the first call to sqrt gets the answer and the second call just refers to the answer produced by the first call. That is not what happens. The first line computes sqrt(x) and ignores the answer. The second line recomputes sqrt(x) and stores its answer into y.
Writing a semicolon at the end of an expression converts the expression into a statement.
Use return-type void to indicate that a function does not return a result, meaning its result must be ignored.
int y = 30; y+1;Answer
What are the values of variables r and w after the following statements are done?
int r = 24; int w = r+1; w+1; r++;Answer
double z; z = 4.0; sqrt(z);Answer
Assuming that z is a variable of type double that has already been given a value, what is the correct way to change z to hold the square root of its current value? Answer
If you want to get the square root of z, do you have to change a variable? Answer