Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this syntax: "ACGT"[(int)qrand() % 4]

Tags:

c++

qt

I'm looking at a Qt specific C++ solution for the typical producer/consumer problem. Here's the code for the producer:

class Producer : public QThread
{
public:
    void run()
    {
        qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
        for (int i = 0; i < DataSize; ++i) {
            freeBytes.acquire();                                 // (1)
            buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];   // (2)
            usedBytes.release();
        }
    }
};

I am not able to understand the second line in the for loop viz. "ACGT"[*] syntax. What does it do exactly? Is this Qt specific or is this C++ syntax I'm not aware of?

PS: Full source code here

like image 247
Code Poet Avatar asked Jan 11 '23 14:01

Code Poet


1 Answers

It generates a random characted from: A, C, G, T.

Literal "ACGT" is an array of type char const [5] then [(int)qrand() % 4] is a random index in a range from 0 to 3 including.

like image 190
Juraj Blaho Avatar answered Jan 18 '23 09:01

Juraj Blaho