how to set a int value passed by parameter to a function and assign it to global so I can use outside of the function?
Example:
int assignValues(int valor_assign1, valor_assign2){
valor_assign1 = 7;
valor_assign2 = 3;
}
main (){
int valor1 = 0;
int valor2 = 0;
assignValues(valor1,valor2);
printf("%d,%d",valor1, valor2);
}
The output is actually 0,0 I want it to be 7,3 how do I do this?
I know its a simple question but I've been trying and searching but I can't find anything like that =/
Thanks in advance.
You could pass a pointer to your integers into the function, instead of passing the values. E.g.:
int assignValues(int *valor_assign1, int *valor_assign2){
*valor_assign1 = 7;
*valor_assign2 = 3;
}
main (){
int valor1 = 0;
int valor2 = 0;
assignValues(&valor1, &valor2);
printf("%d,%d",valor1, valor2);
}
You might want to read a pointer tutorial, however.
Pass the pointers:
int assignValues(int *valor_assign1, int *valor_assign2){
*valor_assign1 = 7;
*valor_assign2 = 3;
}
main (){
int valor1 = 0;
int valor2 = 0;
assignValues(&valor1,&valor2);
printf("%d,%d",valor1, valor2);
}
You pass pointers to the variables:
void assignvalues(int *v1, int *v2) {
*v1 = 7;
*v2 = 3;
}
But, in your snippet, valor1
and valor2
are not global. They are local to main
. If they were global, you could just assign to them
#include <stdio.h>
int valor1; /* global */
int valor2; /* variables */
int assignvalues(void) {
valor1 = 7;
valor2 = 3;
}
int main(void) {
printf("%d, %d\n", valor1, valor2);
}
Note: the usage of globals is frowned upon. Your usage, with local variables, is much better.