What is the meaning of the "&" (commercial) operator in the C language?

Asked

Viewed 22,927 times

18

I am putting together a workbook in C and I am looking for a clear way to explain this operator to the reader, and I believe that this question will help the people who are starting.

Take an example:

Code

#include <stdio.h>
#include <stdlib.h>
 
int main ()
{
    int   idade;
    printf("Digite sua idade ");
    scanf("%d", &idade); 
    system ("pause");
    return(0);
}

From what I understand %d and a format specifier which can be used to read or display a variable of type inteiro.

What is the operator meaning &?

2 answers

25


In this context is the "address" operator. Then the result of it will always be the memory address of the object in question (in general the location where a variable is allocated in memory). That is, it creates a pointer.

This is the typical form of C to pass an argument to a function. In C this passage always has to be explicit, since all passages are given by value (in general the languages are like this, but some hide this and it seems that they are passing by reference). In this case it is passing the value that is the memory address, which will be interpreted somewhere taking the value being pointed by this address, thus creating a indirect.

In the specific case the scanf() expects just an address where it should store what is typed by the user. That is why it is being passed with this operator.

For this function it does not matter the value saved in the variable but where it is.

A common mistake is for the inexperienced programmer to use this operator in a variable that is a pointer. There you don’t need it, because the variable already contains the address of the pointed object (unless you want a pointer to pointer, but this is not common).

The code scanf("%d", &idade); can be read as: "read data in full decimal value format and store at the age address".

The opposite operator is the * which is to take the amount indicated by the address.

Not to confuse the operator & used in another context that makes a calculation of and in bits, is the same symbol, but another operator.

In C++ it is also used as another operator or declarer to indicate reference (which only exists concretely in this language and not in C) which is similar but somewhat different from pointer.

  • Thank you very much ! do you think I should leave the title like this ? I could not think of any other, I think so is ok.

  • 3

    I think it’s good, if I think of something better, I’ll edit.

5

The operator & extracts the memory address of a certain variable, which can be used for a wide variety of things.

Examples:

Suppose you want to create a function that adds an integer x to an integer variable y. What many laymen and beginners would do is:

#include <stdio.h>

void adicionar( int x, int y){
    y += x;
}

int main(){
    int a = 5, b = 2;
    printf("Valor inicial de b: %i\n", b);
    adicionar(a, b);
    printf("Valor final de b: %i", b);
    return 0;
}

Output:

Valor inicial de b: 2
Valor final de b: 2

Yeah, but we don’t ask the function adicionar that the value of variable b is modified? Unfortunately that’s not how things work: When we pass b to function adicionar, we spent a copy from b to function. Why does this happen? Because the function requested the value contained in b, and not its memory address. Thus, it is impossible to modify the original variable b.

We can think of this situation as follows: In function adicionar:

void adicionar( int x, int y){
    int x = x;
    int y = y;
}

That is, when a function requires a valor of a variable, it’s as if internally it recreates the variables that we’ve gone through, only in its own scope. Thus, the variables that we pass as an argument are ignored, and the variables of the function scope are used.

To solve this unfortunate problem, an alternative would be to modify the add function as follows:

void adicionar( int x, int *y){
    *y += x;
}

Here, we ask for a pointer for integer y. This basically means that we are requesting a memory address for a variable, that is, a memory location that we will modify within the function. The code snippet *y += x basically makes the dereference of the y pointer, and adds to that dereference the value x. For ease of understanding, we could write the following pseudo-function code:

void adicionar( cópia de inteiro x, ponteiro para inteiro y){
    Desreferencie, ou seja, obtenha o endereço de memória para o qual y aponta.
    Em seguida, some a cópia do valor de x ao ponteiro recentemente desreferenciado.
}

In that case, we can do the following in our role main():

int main(){
    int a = 5, b = 2;
    printf("Valor inicial de b: %i\n", b);
    adicionar( a, &b);
    printf("Valor final de b: %i\n", b);
    return 0;
}

Output:

Valor inicial de b: 2
Valor final de b: 7

But what is this one & which we entered before b when calling the add function? What does it do? Very simple: It passes a pointer to a memory address! It is as if we are implicitly starting the parameter y of the prototype of our function with the address of b! Thus, when we deviate y within the function adicionar, we are making sure that the address of b, to which y is pointing, has its value modified!

Therefore, it is concluded that & is an operator that allows us to access and modify a memory address of a variable.

We could also modify the contents of b without the use of functions using pointers indirect coupled to the use of the operator &. For example:

#include <stdio.h>

int main(){
    int a = 5, b = 2, *c = NULL;
    c = &b; //c agora aponta para o endereço de b, obtido com o operador &.
    *c += a; //O valor contido no endereço para qual c aponta (b) é igual a ele mesmo mais a.
    printf("O valor de b é: %i", b);
    return 0;
}

Output:

O valor de b é: 7

Another use of &, less known to beginners, is for carrying out the logical operation AND. For example:

if((24 & 50) > 30){
    puts("(24 & 50) é maior que 30.");
}
else{
    puts("(24 & 50) é igual ou menor que 30.");
}

Knowing that & represents, in this case, the logical operation AND, obtained:

0    0    0    1    1    0    0    0
0    0    1    1    0    0    1    0
____________________________________
0    0    0    1    0    0    0    0

As the result obtained is 16 on the decimal basis, the output of this conditional structure is:

(24 & 50) é igual ou menor que 30.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.