2

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.

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.

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.

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.

So I changed question title a little and added this text.

4

1 回答 1

1

...通过使用宏来实现错误:

int main () {

 #define int const int
 #define float const float

 int x = 5;
 float y = 5.3;

 #undef int
 #undef float

 return 0;
}

你甚至可以将这些 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;
}

但我不确定这种风格是否可以。

于 2012-08-08T12:40:55.093 回答