Martin Deegan Martin Deegan - 6 months ago 26
C++ Question

What does this C++ function do?

I need to bit bang an I2C device and I came across this code on Wikipedia.

#define I2CSPEED 100

void I2C_delay(void) {
volatile int v;
int i;

for (i = 0; i < I2CSPEED / 2; ++i) {

I'm confused on what


How long does this delay for?

Answer Source

Likely this was for a platform where accessing a volatile variable forces an actual memory read operation. If that's true, then the loop will likely take at least as long as 100 memory reads. It may take longer, depending on the way the CPU is designed.

Note that on most x86 CPUs that typical computers are likely to use, there will be no actual memory reads here. But presumably this was for something like a Raspberry Pi.

The Wikipedia page that contains this same code makes clear that it's pseudo-C and not intended to be code that you'd actually run but more of a guide for writing code. If you were actually going to use this code, you should probably replace that loop with a proper delay function for your platform.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download