Difference between assigning variables by value or reference


I have seen several pieces of code in c where when assigning a value to a variable they do not use the '&' and I've read that it's something about value or reference, could someone explain to me?

char userName[25];   
printf("Ingresa tu nombre de usuario: \n");
scanf("%s", userName);

or also use the

int num;
printf("Ingresa un numero: \n");
asked by darioxlz 04.01.2018 в 16:59

1 answer


When passing a variable to a function by value, what is done is to pass a copy of the information contained in that variable, so we will have two different instances of the same variable; one that is in the middle in which it was sent and another that is in the middle where it was sent. So if the information of the sent variable is modified, it will only be changed in that environment.

When passing a variable to a function by reference, what we do is actually pass a pointer to the address in memory in which the variable is located, so when modifying the information by means of the pointer in the method to which it was sent it will be modified in all the fields since we actually modify the original variable, in fact the only one since this form does not make another copy of the variable.

for example

//declaro funciones
int sumarXvalor(int a,int b);
void sumarXreferencia(int a,int b,int *resultado);

int main( ) {
 int a = 0;
 int b = 0;
 int resultado = 0;

 //por valor 
 printf( "paso de valor por valor" );
 resultado = sumaXvalor( a, b );

 // por referencia
 printf( "Paso de Parametros por ReferencianPasamos el valor de posicion en memoria de la variable resultado: %pn", &resultado );
 sumarXreferencia( a, b, &resultado );
 printf( "Resultado: %in", resultado );
 return 0;

int sumarXvalor( int a, int b ) {
 return a+b;

void sumarXreferencia( int a, int b, int *resultado ) {
 *resultado = a + b;

I hope it helps you, a long time ago I do not play C, sorry if there are any mistakes, greetings.

answered by 04.01.2018 / 17:16