FAQ Database Discussion Community


Is there any reason I wouldn't use “let”?

javascript,const,var,ecmascript-6,let
Now that we can write ES6 and deploy it to browsers (using Traceur or 6to5 to support legacy user agents), is there any reason why we wouldn't use let or const as our default keywords for variable declaration? Is var dead? And if it is, can I configure my linting...

C++ overload resolution, conversion operators and const

c++,const,overloading,operator-keyword
In this case void f(int *); void f(const int *); ... int i; f(&i); the situation is pretty clear - f(int *) gets called which seems right. However, if I have this (it was done like that by mistake(*) ): class aa { public: operator bool() const; operator char *();...

Reassigning const char array with unknown size

c++,c,arrays,char,const
So i have this 2 arrays inside my main function: const char* basket[]; const char* basket_peach[] = {"1 1111 2 0000","2 2222 2 0000", 0}; ... if (strcmp (c_id,"somebasketid") == 0){ basket = basket_peach; } ... If i try to do this: ... if (strcmp (c_id,"somebasketid") == 0){ const char*...

Returning a const pointer to a const data member and the 'auto' keyword. A bit confused

c++,pointers,c++11,const,auto
I've recently been learning C++ and just today have been introduced to const and the concept of const correctness. In an attempt to better understand the theory, I've been writing a series of simple programs to make sure that I understand the concept correctly. I thought I understood everything, but...

Why is erasing via a const_iterator allowed in C++11?

c++,c++11,stl,const,erase
As of GCC 4.9.2, it's now possible to compile C++11 code that inserts or erases container elements via a const_iterator. I can see how it makes sense for insert to accept a const_iterator, but I'm struggling to understand why it makes sense to allow erasure via a const_iterator. This issue...

Using const int as array size

c++,arrays,const
Why am I able to use a locally declared const int as the size of an array declaration but am not allowed to do the same with a const int passed as an argument? For example, in the below code why do I get compiler errors only on line 2?...

Confusing warning about a constant decimal field in C#

c#,const
I was experimenting with the const modifier while exploring a plethora of C# tutorials, and placed a bunch of const modifiers in a class like this without actually using them anywhere: class ConstTesting { const decimal somedecimal = 1; const int someint = 2; ... } With this class, I...

How would I convert a const Class* to a Class*?

c++,linked-list,const
I'm trying to insert something into a linked list, but the compiler tells me that I can't convert from a const Student* to a Student*. Each node contains a Student *stud and a Node *next. This is what I have written so far of the function: void LinkedList::putAtTail(const Student &student){...

Whats the best way to do strlen(const)?

c,string,const
I am creating a C program with some hardcoded parameters. (This is by design, lets not worry about that.) //global constants const char * const USERNAME = "username"; const int USERNAME_LEN = strlen(USERNAME); Of course, this errors out because strlen isn't a constant apparently. Is there a way to do...

int* to Constant Array

c++,arrays,pointers,const,quotation-marks
I asked this question: Array Equivalent of Bare-String To which the answer was C++ doesn't provide this functionality for const int*s. Which is disappointing. So my question then is: In practice how do I get around this limitation? I want to write a struct like this: struct foo{ const char*...

Why it is allowed to initialize static variable with non const here?

c,gcc,initialization,const,static-variables
I was reading this. The first answer by @Andrei T says that A "large" object is never a constant expression in C, even if the object is declared as const. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects...

std vector no match for operator ==

c++,vector,const,operator-keyword
I'm stuck at this error: gcc.compile.c++ Physics/HelicityAmplitude/bin/gcc-4.8.3/debug/HelicityDecayTree.o In file included from /cvmfs/cluster/gcc/gcc-4.8.3/include/c++/4.8.3/algorithm:62:0, from /cluster/compwa_externals/boost_1_55_0/include/boost/move/algorithm.hpp:23, from /cluster/compwa_externals/boost_1_55_0/include/boost/move/move.hpp:24, from /cluster/compwa_externals/boost_1_55_0/include/boost/unordered/detail/util.hpp:19, from...

const methods in golang?

c++,go,const
In golang, often you want to declare a pointer-type associated method, because you don't want to copy a huge struct around: func (a *HugeStructType) AMethod() { .... } In C++, when I wanted to make such a method, but guarantee that it didn't mutate the underlying struct, I declared it...

Passing Image*[3] to const Image*[3] cannot be done with const_cast, alternatives?

c++,arrays,casting,const
I have a function that takes in an array of pointers to images that will not be modified, defined as: void processImg( const Image *myImgs[NUM_IMAGES] ); I'd like to pass in a non-const type. I would expect to need to do this, but it is illegal (VS2010 says not allowed):...

Changing const member within class

c++,initialization,const,subclass
I would like to let a const int be changed by a function within a class. class Parent { int currentIndex; private: initMember(const int& member) { member = currentIndex++; } } class Child { const int Member1; const int Member2; Child () { initMember(Member1); initMember(Member2); } } Who ever writes...

How to modify a const reference in C++

c++,const
I am new to C++ and I am trying to modify some existing code. I basically have to modify a const reference variable in C++. Is there a way to do so? I want to remove a subtring from a constant string reference. This obviously wouldn't work, since id is...

Is this an appropriate use of const qualifiers in C?

c,const
I have a simple vector implementation in C, which holds an array of void*. It's up to the user to take care of the actual type. I want to 'promise' that the vector will not alter its contents, so I store data as: Struct _Vector{ UInt32 used; UInt32 size; const...

I dont know how to make a “const unsigned float&”

c++,const,unsigned
I have this: const unsigned float& distanceTo(const Point2D&){...} but VS2013 says me that I have an invalid combination of type specifiers, how I must put the specifiers to return a constant reference to an unsigned float?...

Testing template based class with const template parameter which has to be varied

c++,templates,testing,const,const-cast
I am developing a template based library to support fixed point integers and I came up with this class and now I have to test it for various values of INT_BITS and FRAC_BITS. but since they are const (and they have to be so for a reason), I am unable...

What's the c++ standard in const postion in parameter passing?

c++,const
If I'm not wrong, these function parameters: void foo(const Type& type); void foo(Type const& type); are equivalent. What is the standard way to declare them? By using the first or the second function declaration? With "standard" I mean the most readable and used version, if ISO C++ does not define...

The address of const variable, C++

c++,const
Recently I was rereading the Effective C++ by Scott Meyers (3-rd edition). And according to Meyers: "Also, though good compilers won’t set aside storage for const objects of integral types (unless you create a pointer or reference to the object), sloppy compilers may, and you may not be willing to...

Const declaration curiosity

c++,const
Ok, so i'm doing some exercise from a book, and I saw this declaration float f, const c =9.9; Initially, I thought this would be a compiler error, but I went into VS2013 and tested this, and it did not throw an error. I could even modify the c variable...

Not understanding C++ type mismatch: const Foo* to Foo* const&

c++,pointers,reference,const
Having this set of objects and statements: QSet<Foo*> set; iterator QSet::insert(const T & value) //type of the function I want to call const Foo * get() const //type of the function I use to get the argument set.insert(get()); //the line showing up as error I get the error "no known...

C++ Is “const void” As Return Value More Const-Correct Than “void”? [duplicate]

c++,const,void
This question already has an answer here: Should useless type qualifiers on return types be used, for clarity? 6 answers I have become somewhat of a const-correctness fanatic when it comes to programming. I've got const's everywhere (where correct of course). Now I've even started const'ing my void return...

C++ data grouping class and const access

c++,const,class-design
This question deals with class design and coherent interfaces (I guess). Say you have a small class to represent the "Geometry" of a road... It could contain many properties and methods like this... class RoadMap { private: struct RoadPiece { float x1, y1, x2, y2; }; std::string name; float area_width;...

What's a const variable inside? [duplicate]

c++,c,const,point
This question already has an answer here: Const variable changed with pointer in C 5 answers #include <stdio.h> int main() { const int a=1; printf("a's address is %p\r\n",&a); printf("input a's address\r\n"); int *p=NULL; //here let p point to a; scanf("%p",&p); printf("p point to %p\r\n",p); *p=100; // I suppose a...

Copy constructor used in a “for” loop, but where?

c++,constructor,iterator,const,implicit-conversion
I'm writing an UTF-8 string class and it's two const and non-const iterator classes. I'm encountering a const problem. Here are the classes : class Utf8String { public: class ConstIter; class Iter { friend class ConstIter; private: Iter(); private: Utf8String * m_pStr; utf8::iterator< char * > m_oIter; public: Iter( const...

Check if string can be mutated in C

c,arrays,string,const,constants
Say I have this function: void f(char *s) { s[0] = 'x'; } This function will sometimes cause errors and sometimes not. For example, char *s = "test"; f(s); // Error char t[] = "test"; f(t); // Success Inside function f, is it possible to determine whether or not s[0]...

How to make a method const based on the template parameter?

c++,const
I have a class with a template parameter, and I want to call a method of it. It looks something like this: template <typename T> class Foo { public: void doSomething() { for (auto& t: ts) { t.doSomething(); } } private: std::vector<T> ts; }; This works, but I want to...

Is it possible to write two template functions as one when the only difference is the const-ness of an argument?

c++,templates,const
I have something like: template <class Foob, class T> void do_it(Foob& f, T& t) { f.proc(t); } template <class Foob, class T> void do_it(Foob& f, const T& t) { f.proc(t); } Some Foobs take const T&s while other Foobs take just T&s, or the same Foob may even have two...

Modification of const int through a non-const pointer

c,pointers,const
#include <stdio.h> int main(){ const int a = 10; *(int*)(&a) = 9; // modify a printf("%d", a); return 0; } When I run this code on Xcode, the output is 10 (not changed) When I run this code on Visual Studio Community, the output is 9 (changed) Why?...

Understanding how read the `const`ness of c++ code

c++11,const
In my attempt to teach myself C++, I was hoping to get some help in how to read the const-ness of a expression/function etc. For example, the code below: const screen &display(std::ostream &output) const { do_display(output); return *this; } In the above code. there are two const declarations in the...

constexpr const vs constexpr variables? [duplicate]

c++,c++11,gcc,const,constexpr
This question already has an answer here: Difference between `constexpr` and `const` 3 answers It seems obvious that constexpr implies const and thus it is common to see: constexpr int foo = 42; // no const here However if you write: constexpr char *const str = "foo"; Then GCC...

Will removing 'const' from a variable in my C++ cause me issues later on?

c++,const
I am debugging some C++ code, and want to change the value of a variable inside a particular function. That variable was passed as a parameter to the function using the const keyword, for example: void setRequest(const &data){ ... } I now want to change the value of the variable...

Access to reference in member variable discards constness

c++,c++11,reference,compiler-errors,const
I made a wrapper around an object in my code that should modify accesses to the object. I choose to use an object here for testing instead of a functor that would have the same functionality. Basically: The wrapper receives a reference to the object and forwards all indexed accesses...

Error in accessing a 2D array inside a class

c++,static,const,multidimensional-array
I have been working on a code in C++. But, I got stuck at a point. This is a small prototype of my code:: #include <iostream> using namespace std; class Test{ private: const int var; void funPrivate(int arr[][var], int temp){ cout << arr[0][0] << endl; } public: Test(int n) :...

How to use Const Type Class in OOP C++?

c++,oop,const
Could you explain why I cannot use the const type in a class? Example code: class Array { int *Arr; int n; public: Array(int _n = 0) { Arr = new int[_n]; n = _n; } ~Array(void) { delete []Arr; } friend void f(const Array &A) { A.Arr[0] = 3;...

Using .size() vs const variable for loops

c++,vector,coding-style,const
I have a vector: vector<Body*> Bodies; And it contains pointers to Body objects that I have defined. I also have a unsigned int const that contains the number of bodyobjects I wish to have in bodies. unsigned int const NumParticles = 1000; I have populated Bodieswith NumParticles amount of Body...

Aliasing a variable using const reference

c++,reference,const,alias,const-reference
When dealing with T instances obtained from an array or trough any other longish syntax, I often use a const T& to alias the object and make my code more readable (of course only if the lifetime of the object allows it). I've seen this elsewhere, e.g. here on Stefan...

Why must const class members be static to be properly optimised?

c++,optimization,const
Given: class Foo { const int x = 5; public: inline int get() { return x; } }; class Bar { static const int x = 5; public: inline int get() { return x; } }; int fn0(Foo& f) { return f.get(); } int fn1(Bar& b) { return b.get(); }...

Initialize a const vector in a class constructor (C++)

c++,class,vector,const,member-functions
I am trying to figure out how to initialize a const class member variable, (in this case a vector), to some arbitrary values in the class's constructor. Basically, in the class definition, I have: const vector < pair <float, float> > myVector; In the class's constructor however, I would like...

C++11 MinGW 4.9.1 shared_ptr and const static class field result “Undefined reference”

c++,c++11,static,const,mingw32
#include <memory> class CItem { private: int m_inner; public: static const int CAP = 1; CItem(int temp) : m_inner(temp) {} }; typedef std::shared_ptr<CItem> TPItem; int main() { int tttt = CItem::CAP; CItem *temp = new CItem(CItem::CAP); TPItem temp2(temp); TPItem temp3 = std::make_shared<CItem>(tttt); TPItem temp4 = std::make_shared<CItem>(CItem::CAP); //On MinGW there error:...

std::unique_ptr to transfer ownership of a const object

c++,c++11,const,unique-ptr,ownership
I have an object of class A created inside a method. This method also creates an instance of an object B that takes as constructor argument the object A just created. B has to take the ownership of the object A but it can't modify it. This means that A...

Mutable vs Lazy Evaluation

c++,const,lazy-evaluation,mutable
Recently I was reading this faq on const-correctness. Now I came across the following situation where I dont know what to make const or mutable. Assume the simple example: class Averager { public: Averager() : sum(0),isUptoDate(false),N(0){} void add(double x){ sum+=x; N+=1; isUptoDate = false; } double getAverage() const { if...

How do you correctly initialize a struct with a member that is a const pointer to a const value?

c++,pointers,struct,const
Currently I'm doing something like this: struct foo { const int *const a, *const b, *const c; foo(int a, int b, int c) : a(_a), b(_b), c(_c) { *_a = a; *_b = b; *_c = c; } private: int _a[1], _b[1], _c[1]; }; but is there a way to...

Changing constant memory content through non-const pointers in C

c,pointers,segmentation-fault,const
Let's say I declare this variable in C: const char*** const strings; Now if I try this: printf("character is : %c \n",***strings); **strings="hello"; printf("strings is %s \n", **strings); printf("character is : %c \n",***strings); Sometimes, I get the following output: character is : strings is hello character is : h However...

Can't initialize array with struct containing function pointer -error: initializer element is not constant

c,arrays,const,function-pointers,array-initialization
I'm trying to initialize an array of structs. The struct contains a function pointer as one of its data members. But my compiler is giving me an error complaining that The initializer element is not constant. How can I initialize the array with my declared function pointer? typedef void (*write_func_ptr_t)(...

Passing a struct to a template with extern const. What is the extern for?

c++,templates,struct,const,extern
I am asking myself why the following code works and what the specifier extern does when instantiating baz_instance: struct baz { int value; }; extern const baz baz_instance = {3}; template<baz const& b> int foo(){ return b.value; } int main(){ foo<baz_instance>(); return 1; } Why does the above code compile...

loop through constant enum #define

c++,loops,enums,const
i have a const enum in my c++ code and i wanna know if i could loop through those colors with by example an integer reference to each member of this enum const enum Colors { #define WHITE(alpha) D3DCOLOR_ARGB(alpha, 255, 255, 255)// #define RED(alpha) D3DCOLOR_ARGB(alpha, 255, 000, 000)// #define GREEN(alpha)...

Can I declare a variable as const in the public header and not in the private header?

c,linker,const,header-files
For example, can I do something like this so that only foo.c can modify the variable foo?: foo.h: extern const int foo; void foo_init(void); void foo_reinit(void); foo.private.h: int foo; void foo_init(void); void foo_reinit(void); foo.c: #include "foo.private.h" void foo_init() { foo = 1; /* ... */ } void foo_reinit() { foo++;...

Mutating copy of string and returning value instead of changing original string

c++,string,recursion,const
I have a recursive function which uses string and the operation i perform are erase, replace, insert,.. int method(original_string): ... min(operation1(original_string), operation2(original_string)) ... I want to keep the original string unchanged but rather need a mutated new string mutate(original_string, operation) : temp = copyof(original_string) operation(temp); return temp; Because the problem...

variable global const “macros” in C++ and optimal design patterns

c++,design-patterns,mfc,const,global
I inherited some 10 year old code I have to complete. The code is in MFC (C++). There's a .h file where the custom data structures are written and some const variables are in there as Globals. Some of these are used for MS Office file extensions, of type CString,...

Why pass by value and not by const reference?

c++,function,arguments,const
Since const reference is pretty much the same as passing by value but without creating a copy (to my understanding). So is there a case where it is needed to create a copy of the variables (so we would need to use pass by value).

Specifying function call to const vs. non-const?

c++,reference,const
In my code I am specifying two functions that do the same thing, except one returns a const object and is specified as const: const Object& getObject(...) const {...} while the other is not: Object& getObject(...) {...} When I try to call getObject like this: Object o = getObject(...); it...

When should I use const& to this?

c++,reference,const,this
I found some code like this: class foo{ int a; public: foo(int v) : a{v} {} bool operator==(const foo& rhs) const&{ return (rhs.a == a); } }; It compiles and runs. I was wondering what are the benefits (or drawbacks) of having the reference (&) to this in the operator==....

Int& to const int -static vs dynamic-

c++,dynamic,reference,const
class A { public: A(int i = 25) {x = i;y=new int[i];for(int j=0;j<i;j++) y[j]=j;} int& f() const {return x;} int& operator[](int i) const {return y[i];} private: int x,*y; }; int main() { A a(15); cout << a[5]; cout << a.f(); return 0; } When I'm trying to compile the code...

What is the difference between final, const and static variables in java

java,variables,static,const,final
What is the difference between final, const and static variables in java with code example please `

extern variable and array declare issue c++

c++,arrays,global-variables,const,extern
I have a problem with an extern variable and an array declaration with it. How to declare an array with global variable which located not in the declarable file. file1.cpp const int size = 10; mainfile.cpp extern const int size; void main() { int mas[size]; } int mas[size]; This line...

Different value when converting char*

c++,char,const
I have to convert token[1] to vm_address_t, but when doing so the original value is lost. Any idea how to convert / cast it right ? Here is my code: char* ConvertToC(string value){ char *cvalue = &value[0u]; return cvalue; } const char* getOffsetToken(string value){ const char *offsettoken; int n =...

Is there anything wrong with using static const structs to limit name collisions of constants in C?

c,struct,const,constants,name-collision
For example, if I were to create a hierarchical static const struct like this in a header (.h) file: static const struct { struct { char STATIC /* = 0 */; char DYNAMIC /* = 1 */; } ALLOCATION; struct { char TABLE /* = 0 */; char LIST /*...

Member functions that are sometimes const

c++,const
I have a class design similar to the following: class MyClass { public: bool IsValid() const; void MakeValid(); private: bool CheckValidity(bool fix); }; bool MyClass::IsValid() const { // Check validity, but don't fix any problems found. Doesn't work. return CheckValidity(false); } void MyClass::MakeValid() { // Check validity and fix problems...

What is the difference between int const function(parameters), int function(const parameters), and int function(parameters) const?

c++,const
I'm working on an assignment for my CS class and it uses const, and I am kind of confused as to when to use each. What are the differences between these 3 functions? int const function(parameters) int function(const parameters) int function(parameters) const Thanks in advance!...

How does extern work in namespaces?

c++,namespaces,global-variables,const,extern
I'm running a simple program similar to what I found here. It's meant to reduce code bloat when including constants in multiple files. It does this by using const global variables within a namespace with their respective extern forward declarations. globals.h #ifndef GLOBALS_H_ #define GLOBALS_H_ namespace Constants { // forward...

Alias the return type of a const overloaded function

c++,c++11,const,decltype
I have the following overloaded function : template<size_t N, typename T> auto get(const T & _t) -> decltype(std::get<...>(_t)) { ... } template<size_t N, typename T> auto get(T & _t) -> decltype(std::get<...>(_t)) { ... } First question is : does the first one uses std::get(const tuple<_Elements...>& __t) and the second one...

Cant find resolution for the error “invalid conversion from char to const char*”

c++,string,char,border,const
I have looked around but cant find an answer to my question. The program is suppose to put a border of stars (*) around a heading, but I'm getting the error: invalid conversion from 'char' to 'const char*' [-fpermissive] as well as the error initializing argument 1 of 'std::basic_string<_CharT, _Traits,...

Why can't I push_back to a vector of const elements? [duplicate]

c++,vector,const
This question already has an answer here: Does C++11 allow vector<const T>? 1 answer push_backing to a vector of non-const elements works as expected: std::vector<int> foo; int bar = 0; foo.push_back(bar); But why is the following not possible? std::vector<const int> foo; const int bar = 0; foo.push_back(bar); More precisely,...

Why STL containers can insert using const iterator

c++,stl,iterator,const
Why STL containers can insert using const_iterator? For example, there is iterator std::list::insert (const_iterator position, const value_type& val); I have thought that const_iterator's does not allow to modify container....

Why are non-const vector elements const?

c++,vector,boolean,const,extraction-operator
When I iterate over a vector<bool>, I find that the elements, dereferenced through the iterator, are recognized as if they were const. Why is that? Change either the container or the element type, such as list<bool> or vector<short>, and the elements are non-const. This code shows what I'm talking about:...

Why Can't I move an Element of a map?

c++,dictionary,key,const,move
I want to be able to change the key of an element of a map. I thought that a good way to handle that would be to move the element from the map, as follows: map<char, int> foo{{'a', 1}, {'b', 2}, {'c', 3}}; foo['z'] = move(*foo.find('c')).second; for(auto& i: foo){ cout...

overloading a function which differs from the original only by “const” in parameter list [duplicate]

c++,const,function-overloading
This question already has an answer here: Overloading reference vs const reference 2 answers I have a question about overloading a function with only difference in "const". For instance, if there is a function A, which is pass-by-reference, it is ok to overload it by pass-by-reference-to-const. However, when will...

What's the equivalent of std::is_const for references to const?

c++,types,const
Consider the code: int const x = 50; int const& y = x; cout << std::is_const<decltype(x)>::value << endl; // 1 cout << std::is_const<decltype(y)>::value << endl; // 0 This makes sense, because y is not a const reference, it is a reference to a const. Is there a foo such that...

const& vector member initialized with const& vector in ctor

c++,c++11,vector,reference,const
I have the following code in which I have member v_, a const reference to a vector of ints. It is initialized with an lvalue, so my thinking is this should not cause any copy. #include <iostream> #include <iterator> #include <vector> using Vec = std::vector<int>; void out(Vec const& v) {...

Difference between static and const variables [duplicate]

c#,variables,static,const,global
This question already has an answer here: What is the difference between Const and Static in C#? 5 answers what is the difference between "static" and "const" when it comes to declare global variables; namespace General { public static class Globals { public const double GMinimum = 1e-1; public...

Function return value defined as a constant [duplicate]

c,function,const
This question already has an answer here: Purpose of returning by const value? [duplicate] 6 answers I've seen in several occasions functions to be defined with the const type qualifier just like that: const int foo (int arg) What is the point in this? Function's return value cannot be...

Optimization of #define vs static const (in avr-gcc)

c,gcc,optimization,macros,const
Although I welcome answers on this on a general scope, I'm asking primarily for avr-gcc to make this not too broad. I have looked at some questions, particularly this and this one. They mostly look at semantic differences, e.g. that a static const can't be used in place of a...

Casting a const parameter in a function pointer to a non const in C++

c++,function,pointers,const
I have a function that behaves almost the same whether I do a call to read(...) or write(...) that handles transfers to and from a file descriptor. I want to write a function like this: uint32_t handleTX(ssize_t (*func)(int, void *, size_t)); I also have two functions: uint32_t myRead() { return...

Get address from const

pointers,const,nim
From the manual: One can get the address of variables, but one can't use it on variables declared through let statements I understand this is done to provide safety. Now, if i want to get the address from a const at all cost is there a workaround?...

Converting form CString to const char*

c++,const,c-strings
I've wrote a method that convert form CString to const char *: const char* CAESDlg::ConvertToChar(CString str) { CStringA charstr(str); const char *cstr = (const char *)charstr; return cstr; } but when trying to put it in a const char * it doesn't return the correct value! const char *test =...

How to use const InputIterators to write a function for generic containers?

c++,c++11,stl,iterator,const
I'm trying to understand how to write a (stand-alone)function that takes const InputIterators and does something simple while iterating over every element in the container. For simplicity, I'm considering a simple print function, that would print all elements in the range between [first..last), but the function is not allowed to...

Understanding const operator

c++,const
I'm reading Scott Meyers' book and come across the following example: class Rational { ... }; const Rational operator*(const Rational& lhs, const Rational& rhs); Rational a, b, c; ... (a * b) = c; // invoke operator= on the // result of a*b! He said that it was really wierd...

const variable not hoisted for immediately invoked function

javascript,scope,const,ecmascript-6,hoisting
I was playing around new ECMASCRIPT-6 const key word. I did not understand one particular behaviour of the keyword. Lets say I have two functions First case (function(){ console.log(_t); const _t=10; })(); and Second case function t(){ console.log(_y); const _y=11; } t(); For the first case the output is (didn't...

Read INI to class const PHP

php,class,const
I'm receiving the error Parse error: syntax error, unexpected '(', expecting ',' or ';' on the TEXT line when trying to run the following code. I really need to be able to write the contents to Config::TEXT. Any idea as to where I'm going wrong? class Config { const DB_HOST...

Difference between static const and const on a variable [duplicate]

objective-c,static,const
This question already has an answer here: What is the difference between static const and const? 2 answers There is any difference between: #import <UIKit/UIKit.h> const static NSString * name; @interface AppDelegate : UIResponder <UIApplicationDelegate> @end and: #import <UIKit/UIKit.h> const NSString * name; @interface AppDelegate : UIResponder <UIApplicationDelegate> @end...

Non-const copy constructor

c++,constructor,const,copy-constructor,observers
I'm doing copy on write optimization for object (i.e. when calling a copy-constructor just save pointer to an object and really copy it only if we need to change our object, or if object we are pointing to going to change). Before changing our object we need to notify others...

Passing const references to functions

c++,reference,const
I was watching a video and saw this code: class Dog { public: Dog() : age(3), name("dummy") {} void setAge(const int &a) { age = a; } private: int age; std::string name; }; I was curious about the function signature for setAge because I've never used const as a function...

const issue with pointer to pointer

c++,c,pointers,const
I have a function that i'm using to delete buffers. The pointers are passed by address so that the function can also unset them once the memory is released : static void _FreeBuf( const uchar16_t ** pBufPtr ); void Ucs2String::_FreeBuf( const uchar16_t ** pBufPtr ); { assert( NULL != pBufPtr...

Const vs. array-to-pointer conversions

c++,arrays,type-conversion,const,language-lawyer
Is the handling of constness in fa being turned inside out intentional, or does it look like a bug (compiler or the standard)? I can see how this can happen, but it still feels pretty weird (at the very least I would expect a = "qwe" to be treated as...

Const keyword in function with an *& argument.

c++,const,pass-by-reference
can you please explain why in the following code: #include <iostream> void fun(char * const & x){(*x)++;} int main(){ char txt[100]="kolokwium"; fun(txt); std::cout << txt <<"\n"; } keyword const is needed for code to compile? If I remove it I get: invalid initialization of non-const reference of type ‘char*&’ from...

C++: How to convert 'const char*' to char

c++,string,char,const
I know there are a lot of questions like this out there on StackOverflow, but I haven't been able to find any that help resolve my case. Whenever I try to do something like this: // str = some string or char array // some magic to get around fpermissive...

C const array elements are not really const?

c,arrays,const,elements
I read everything and everywhere I could about "compile time constants" in C, and I cannot yet give an explanation to the following: const short testArray[2]={1,2}; //void IndeedConst(void){ testArray[0]=3; } //correctly reports "error: assignment of read-only location 'testArray[0]'" const short testItem=testArray[0]; //why "error: initializer element is not constant"?? so the...