Code problem in ESP32

Not sure if I have this in the right category/forum but I have a problem with a line of code which I resolved but would like to understand why the original code didn't work as expected.
I believe the issue might be in the compiler rather than my code, though admittedly my original approach was poor.

using Arduino IDE 2.2.1 to write program for ESP32.
Board configured is ESP32 Dev Module

I have an array of 24 integers switchArray, where the integers are either 0 or 1 to represent an outlet being on or off.
I am generating another integer switchReg to represent each outlet as a bit in the integer, 8 at a time. Bank represents which group of 8 I am dealing with. Not relevant to the issue, but mentioned it since it is in the code.
Original code:

		for(int outlet = 0 ; outlet <= 7 ; outlet++){
			switchReg = switchReg<<1 + switchArray[bank*8 + outlet];
		}

This had switchReg end up always resulting as 0.

Modification that worked:

		for(int outlet = 0 ; outlet <= 7 ; outlet++){
			switchReg = switchReg<<1 | switchArray[bank*8 + outlet];
		}
T

his worked, where each of 8 bits properly represented the state of each outlet represented in the array.

Although it is bad form to mix bitwise manipulation with integer arithmetic, to me they should produce the same result since switchArray only contains 0 or 1 to represent if the outlet is or should be off or on so adding to the shifted switchReg 0 or 1 should have resulted the same as bitwise OR'ing the 0 or 1 to the rightmost bit of switchReg.

I discussed this with chatGPT, once we understood each other, we suspect the failure of the arithmetic approach may be compiler related.

Any ideas why the addition method ended up with results as 0?

Take a look at C++ operator precedence (which will explain your observation), and you will also see why chatGPT is not a reliable source of advice.

Hint: use parentheses when in doubt.

1 Like

Doh!
Looked up documentation on C++ order of operations and you're certainly right, not that I doubted you.
Thanks a bunch for pointing that out.

Well, the 'workaround' probably made the code more efficient.

Indeed ChatGPT does make mistakes. I certainly don't take its answers as gospel.
But it has help a lot in giving me directions for areas I am not as familiar, such as generating HTML code in C++ (Arduino/ESP32 specifically) and subsequent server side processing of user selections on the webpages.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.