J
J
Johnny Smith2018-06-29 22:00:22
Programming languages
Johnny Smith, 2018-06-29 22:00:22

For x = x + 1, what will x be?


Not a programmer, but someone told
me a long time ago that when x = x + 1, x will equal "2"

#include <stdio.h>

int main(void) {
int x;
x = x + 1;
printf("%d", x);
return 0;
}

Result for some reason: 1!
UPD: in what language can 2 turn out?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2018-06-29
@Rsa97

And what was x equal to before this expression?

J
jcmvbkbc, 2018-06-29
@jcmvbkbc

when x = x + 1 will x equal "2"

x = x + 1 is not an equation. This is a record of the following command: "add one to the current value of variable x and place the result in variable x". Accordingly, the result will depend on the value of the x variable before this command.
If you define a variable as int x;outside of all functions, then C and C++ initially store 0 there. If you do the same inside a function, then the initial value is undefined. Technically, there will be either garbage located on the stack or in the processor register associated with this variable, or some debugging value written there by the compiler specifically to catch calls to uninitialized variables.

M
Mikhail Potanin, 2018-07-06
@potan

Depends on a lot.
In Haskell, for example, this code, if it is clear from the context that x is an integral type, this code will cause the program to abort with a loop error. But if you create your own type that implements Peano arithmetic, then x will become a looped structure, like an infinite list.
In imperative languages, the value of x will depend on the previous value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question