Skip to content

Unfortunate comparison between const and #define in Rust Book 5.27 #25573

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
matthieu-m opened this issue May 18, 2015 · 2 comments
Closed

Unfortunate comparison between const and #define in Rust Book 5.27 #25573

matthieu-m opened this issue May 18, 2015 · 2 comments

Comments

@matthieu-m
Copy link
Contributor

At the end of Rust Book chapter 5.27 const and static is the following extract:

A const can be thought of as a #define in C: it has metadata overhead but it has no runtime overhead. “Should I use a #define or a static in C,” is largely the same question as whether you should use a const or a static in Rust.

Unfortunately, this is rather misleading. An experienced C programmer will try and avoid #define as much as possible (they do have their use) because:

  • a #define is unscoped, and the C preprocessor is just a text preprocessor
  • a #define is untyped

You can check constants - "static const" vs "define" in C for more context and relevant advices; specifically Jonathan Leffer's answer (yep, just skip mine). Note: in C++, the answer is static const because C++ lifts a lot of restrictions for where one can use static const variables.

Since in Rust const is scoped and typed, it is really no equivalent to #define. It is, however, much closer to enum.

Maybe simply comparing to enum instead of #define would avoid confusing the reader?

@steveklabnik
Copy link
Member

We had a chat about this on Reddit, I wanted an issue here for more visibility. Thoughts, anyone else?

@alexcrichton
Copy link
Member

I think it would be fine to add some clarification here, but the emphasis is that the definition is inlined everywhere (like #define), not so much the odd semantics of #define

steveklabnik added a commit to steveklabnik/rust that referenced this issue Jun 9, 2015
This obscures more than it helps.

Fixes rust-lang#25573
steveklabnik added a commit to steveklabnik/rust that referenced this issue Jun 9, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants