intToString – The Each day WTF

[ad_1]

Krzysztof discovered themselves gazing a C++ operate known as intToString. And staring. After which realized that the operate makes extra sense in the event you do not have a look at the identify. Let’s take a peek:

String intToString(u8* p_param, int p_length) {
	int i;
	int j=0;
	for(i=0; i < p_length; i++)
	{
		j = p_param[i];

		if(j==97 || j==98 || j==99 || j==100 || j==101 || j==102 || j==103 || j==104 ||
			j==105 || j==106 || j==107 || j==108 || j==109 || j==110 || j==111 || j==112 ||
			j==113 || j==114 || j==115 || j==116 || j==117 || j==118 || j==119 || j==120 ||
			j==121 || j==122)
		{
		p_param[i] = j-32;
		}

		if(!isprint((char)p_param[i]))
		p_param[i] = 0;
	}

	string s((char*) p_param);
	return s;
}

So, intToString takes a buffer of bytes and a size for the buffer, and at a look, you’d simply assume that somebody is reinventing atoi. We go into the loop, and verify every character, and somebody has opted to unroll a fundamental vary comparability into a protracted collection of or operations. Which is dumb, however… wait a second. ASCII character 97… we subtract 32…

This operate is not an intToString operate. It is a “toUpper operate. Additionally an current operate that did not should be reinvented, additionally a case the place we did not have to unroll the if comparability so laborious.

It is also value noting that String is a typedef for std::string, which is not fallacious however leaves us asking “why?”

[Advertisement]
ProGet’s acquired you coated with safety and entry controls in your NuGet feeds. Study extra.

[ad_2]

Leave a Comment

Your email address will not be published. Required fields are marked *