2
I’m new in C and I made a very simple program that takes two numbers and prints the sum of them:
// Programa que faz uma soma simples
#include <stdio.h>
// Função principal do programa
int main( void )
{
int num1, num2, soma;
printf("Entre com o primeiro número\n"); // Exibe texto na tela
scanf("%d", &num1); // Lẽ o valor e o atribui a num1
printf("Entre com o segundo número\n");
scanf("%d", &num2);
soma = num1 + num2;
printf("A soma é %d\n", soma);
} // fim da função main
I compiled it with gcc and it worked normally, but out of curiosity I decided to do some experiments. When the program requested an input, instead of typing an entire value I put an arithmetic expression and to my surprise it didn’t work? When I enter a sum or subtraction in the first entry it does not request a second entry and prints the result of the operation:
$./soma
Entre com o primeiro número
8+10
Entre com o segundo número
A soma é 18
When I enter an arithmetic expression in the second scanf, the program sums the value of the first entry with the first number of the expression, ignoring the rest:
$./soma
Entre com o primeiro número
5
Entre com o segundo número
2+9
A soma é 7
The strange thing happens when I try to enter with an expression involving multiplication or a floating point number, in which case the program simply returns a random value:
$./soma
Entre com o primeiro número
3*2
Entre com o segundo número
A soma é 1714397539
$./soma
Entre com o primeiro número
3*2
Entre com o segundo número
A soma é 98186483
$./soma
Entre com o primeiro número
3.4
Entre com o segundo número
A soma é 229452083
My question is: Why this strange result when there is multiplication involved?
complementing the answer, the correct is to always check the scanf return value to know the number of fields effectively read
– zentrunix
@zentrunix Yes correct, and thanks for the add-on :)
– Isac
I’m still a little intrigued about this multiplication thing, I think it has something to do with the pointer and stuff. I hope you find out by studying more about C. In this online IDE I was able to simulate the multiplication result, although here it always gives a result close to 2¹ while in my computer it results in quite different values: http://tpcg.io/vaFfFG
– Israel77
@Israel77 It is not about the pointer, but about using values that have not been initialized. It would be equivalent to doing
int x; printf("%d", x);
where you cannot tell which value will show and will normally be a random value which is the value that is in the memory location where the variable was allocated. The random value is usually high because to be low it needed to have many bits at 0, almost all the first bits and this is statistically improbable, although possible– Isac