The following code, excerpted from a much larger program, triggers a C++ compile time error as shown in the leading comments. [Re-]declaring variable 'w' to be a 'const char *' will fix the problem, but I don't know exactly why. I would greatly appreciate it if somebody could elucidate the matter. --TIA

/*  2008-11-03, BG: Example code for compile time problem in X.cpp
 *    The "char *w" line in the code causes compile time error:
 *      [line 25] error C2440: '=' : cannot convert from 'const char *' 
 *       to 'char *' Conversion loses qualifiers
 *    The next line fixes it when uncommented. The actual error occurs on 
 *    the line that calls the string search function strchr(). 

#include "stdafx.h"
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
       const char *e; // e is a pointer to a const char -i.e., 
                         // you can't change the contents of 
                         // what e points to.


	char *w;         // w isn't (a ptr to a const char, that is).
//      const char *w;	  Fixes error produced by previous delaration.
	char c = '9';

	w = strchr(e, c);  // Looking for a pointer to the char '9' in e.

	return 0;
8 Years
Discussion Span
Last Post by Lerner

If you had a pointer to the '9' in the original string you could potentially change the original string. Therefore, since the original string is const, any pointer pointing to any part of the original string should also be const.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.