Is there any way (such as compiler flag) to set ALL local variables const
automatically without the specifier in C/C++/Objective-C? Just like let
semantics in functional languages.
有没有办法(比如编译器标志)自动设置ALL局部变量const而没有C / C ++ / Objective-C中的说明符?就像在函数式语言中使用语义一样。
Because I want to set const
to all local variables, but it's too annoying and makes code less readable. If I can set all local variables const
by default, and I can set some variables mutable
manually, it would be great for me. But I never heard about it.
因为我想将const设置为所有局部变量,但它太烦人并且使代码的可读性降低。如果我可以默认设置所有局部变量const,并且我可以手动设置一些变量可变,那对我来说会很棒。但我从来没有听说过。
If you know something please let me know.
如果您有所了解请告诉我。
Edit
I thought a little more about this after reading responses. And I strongly agree to it would disrupt strong C convention (or standard?) because it's already defined as mutable by default.
阅读回复之后,我想了解更多。我强烈同意它会破坏强C约定(或标准?),因为默认情况下它已被定义为可变的。
So my idea is becoming into another form. Kind of static analyzer. Not compiler. if some tool can check reassigned local variables, and can define any mechanism marking mutable variable (for example, a specific empty preprocessor symbol), it would be perfect tool for me. And also, it won't disrupt C conventions.
所以我的想法正在变成另一种形式。一种静态分析仪。不是编译器。如果某个工具可以检查重新分配的局部变量,并且可以定义标记可变变量的任何机制(例如,特定的空预处理器符号),那么它对我来说将是完美的工具。而且,它不会破坏C约定。
So I changed question title a little and added this text.
所以我稍微更改了问题标题并添加了这个文本。
1 个解决方案
#1
1
... errr sort of by employing macros:
...错误的使用宏:
int main () {
#define int const int
#define float const float
int x = 5;
float y = 5.3;
#undef int
#undef float
return 0;
}
you can even separate these def's and undef's into two different headers, so that your code would look a bit cleaner:
你甚至可以将这些def和undef分成两个不同的标题,这样你的代码看起来会更清晰:
int main () {
#include "all_vars_const_begin.h"
int x = 5;
float y = 5.3;
#include "all_vars_const_end.h"
return 0;
}
But i'm not sure if this style is Ok.
但我不确定这种风格是否合适。
#1
1
... errr sort of by employing macros:
...错误的使用宏:
int main () {
#define int const int
#define float const float
int x = 5;
float y = 5.3;
#undef int
#undef float
return 0;
}
you can even separate these def's and undef's into two different headers, so that your code would look a bit cleaner:
你甚至可以将这些def和undef分成两个不同的标题,这样你的代码看起来会更清晰:
int main () {
#include "all_vars_const_begin.h"
int x = 5;
float y = 5.3;
#include "all_vars_const_end.h"
return 0;
}
But i'm not sure if this style is Ok.
但我不确定这种风格是否合适。