BW> Can someone help me understand why different compilers treat this code
BW> differently?
BW> cout << "The value of /a is " << '/a' << endl;
Because '/a' is not, strictly speaking, Standard C++. Character constants
comprising *two* characters, a forward slash and the letter 'a' in this case,
are a common language extension that compiler vendors supply. However, there
is no agreed-upon standard for their meaning. As you can see:
BW> Borland evaluates 24879. Microsoft 12129...??
Borland gives the character the value 0x2f61, whereas Microsoft gives the
character the value 0x612f. In both cases they are combining the values of
the two individual characters to form a two-byte integer. They are not
agreed, however, on whether the first character represents the high byte or
the low byte. There are good arguments for both choices, as well.
BW> The problem has come up while dealing with command-line args in some
BW> older code I want to reuse, and it's driving me a little nuts.
BW>
BW> while (--argc && **argv++) {
BW> switch (*(int*) *argv) {
BW> case '/a':
No wonder it is driving you nuts. It's exceedingly poorly written code, and,
strictly speaking, code that results in undefined behaviour if any given
program argument string is less than `sizeof(int)' bytes long.
What the code is doing is trying to be sneaky by treating the first two
characters of a string (such as the '/' and the 'a' of "/a") as a two-byte
integer, and then using that integer in a switch statement, relying on the
vendor-supplied extension that allows two-character character literals. As
you have discovered, this code isn't portable, since its behaviour is not
defined.
Forget the argument parsing routine in that program. It's junk. Code your
argument parsing *properly*, using strcmp() and suchlike if you want to
compare strings. Herbert Bushong's code is a good place to start from.
¯ JdeBP ®
--- FleetStreet 1.19 NR
---------------
* Origin: JdeBP's point, using Squish (2:440/4.3)
|