I was looking over this example from my notes and it doesn't include the & operator, &i, before the i when printing over the loop
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; i)
{
printf("%d ", i);
}
return 0;
}
When is the appropriate time to use the & operator and why isn't it used here. Do you only have to use that when using scanf or does it need to be used in printf too?
CodePudding user response:
Generally, you use just the name of an object, like i
, when you want its value. In printf("%d ", i)
, we want printf
to print the value of i
, so we just pass i
.
In scanf("%d", …)
, we do not want to tell scanf
what the value of i
is. We want scanf
to change i
. To do this, we must provide scanf
with some reference to i
. To do this, we give scanf
the address of i
, with scanf("%d", &i)
.
So, when passing an argument to a routine, you will use &
if you want to pass the address of an object to that routine. If you want to pass the value, you will not use &
.
Technically, whenever we write i
in an expression, that designates the object i
, not its value. However, in many cases, an object is automatically converted to its value. So, in printf("%d", i*3);
, the object i
is automatically converted to its value, and then the value is multiplied by 3. This is an automatic part of the language, and it works well, so you rarely have to think about it.
This automatic conversion of an object to its value is called lvalue conversion. There are some exceptions to it. In these cases, we want to use the object i
rather than its value:
- In an assignment, like
i = 3;
, we want the assignment to changei
. - In
sizeof i
, we want the size of the objecti
, not its value or the size of its value. - In
&i
, we want the address ofi
, not the address of its value. - In
i
,i
,--i
, andi--
, we want to modify the objecti
.
In all of those cases, the automatic conversion of an object to its value does not occur. This is part of the design of the C language.
There are two more exceptions:
- With the operator for accessing a member of a structure or union,
.
, the left operand is not converted to its value. So, ifs
is a structure, then, ins.i
,s
remains a designation of the structure, and the expressions.i
then designates the memberi
of that structure. (To continue evaluation of the expression this appears in, that member is then converted to its value, unless it also appears in one of these exceptions.) - If the object is an array, it is not converted to its value. (By separate rules for arrays, it is often converted to a pointer to its first element.)