Help regarding difference between equivalent Rust and C code

Why does the below code works fine in C but fails to compile in Rust?
#include <stdio.h>

int main(){
  
int a=30;
int* p=&a;
a+=10;//works fine in c
printf("%d",*p);//40
}
fn main() {

let mut a=30;

let b=&a;

a+=10;//doesnt compile

println!("{}",*b);
}
I'm a newbie to Rust and having trouble in understanding why cant we mutate the
variable a when we have a reference to it? Why is it designed in such way?

That is the cornerstone of Rust ownerhsip concept: you can't mutate value if there are live references to it.

1 Like

The design prevents bugs.
Variables aren't the same. Rust variables by default have stronger protection than C restrict gives.

Oh I get it.But whats wrong in mutating a variable when we have a reference
to it? What kind of bugs does it prevents?

Race conditions, both single-threaded and multi-threaded.

A famous example of a single-threaded race condition is iterator invalidation, whereby mutating a container can re-allocate its backing buffer, resulting in invalid references.

Multi-threaded race conditions are a kind of obvious consequence – if you can't have multiple threads mutate the same variable at the same time, then data races are impossible by construction.

Preventing these kinds of bugs is basically one of the cornerstones of Rust design.

4 Likes

Thanks for the explanation.I am going to read more about it.

Here's a pre-Rust-1.0 article on the topic. Ignore the technical bits like mentions of @mut or &const (as those changed before stabilization), but read it for the higher-level points about aliasing, data races, and iterator invalidation.

And a quote from another post of Niko's:

Put another way, it’s become clear to me over time that the problems with data races and memory safety arise when you have both aliasing and mutability. The functional approach to solving this problem is to remove mutability. Rust’s approach would be to remove aliasing.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.