sunkue
sunkue

Reputation: 288

Can't I call rand() multy times in a line?

for (int i = 0; i < 12; i++) {
        Vertex v;
        v.pos = (glm::vec3)((GLfloat)(rand() % 100) / 50 - 1, (GLfloat)(rand() % 100) / 50 - 1, (GLfloat)(rand() % 100) / 50 - 1);
        v.col = (glm::vec3)((GLfloat)(rand() % 100) / 100, (GLfloat)(rand() % 100) / 100, (GLfloat)(rand() % 100) / 100);
        tri4.objData.vertices.push_back(v);
        std::cout << tri4.objData.vertices.at(i).pos.x <<"\t" <<i4.objData.vertices.at(i).pos.y<<"\t"<< tri4.objData.vertices.at(i).pos.z << "\n\n";
        std::cout << tri4.objData.vertices.at(i).col.x << "\t" << tri4.objData.vertices.at(i).col.y << "\t" << tri4.objData.vertices.at(i).col.z << "\n\n";

        tri4.objData.indices.push_back(i);
        std::cout << tri4.objData.indices.at(i) << '\n';
    }

this is my GL codes in tihis case, pos.x and pos.y are same.. those three rand()s are return same at 'v.pos=' line or 'v.col=' line.. I did't use srand(time) or something. does rand()s return same values on one line? or vec3 has problem with it?

Upvotes: 1

Views: 102

Answers (2)

Jerry Jeremiah
Jerry Jeremiah

Reputation: 9643

The reason it isn't working for you is that you are using

v.pos = (glm::vec3)(...)

which is casting the stuff denoted by ... into a vec3.

But the ... is three comma separated GLfloat values. The comma operator discards the first two and the third one is casted into a vec3 using the single argument constructor and that's why there is only one value.

You don't want a cast - you want the three argument constructor - so go without the parenthesis:

v.pos = glm::vec3(...)

Here is a comparison between the cast and what you were really trying to do:

#include <iostream>

struct vec3 {
    int x, y, z;
    vec3(int v) : x(v), y(v), z(v) { std:: cout << "vec3(int v)\n"; }
    vec3(int x, int y, int z) : x(x), y(y), z(z) { std:: cout << "vec3(int x,int y,int z)\n"; }
};

int main() {
    vec3 pos = (vec3)(1,2,3); // calls vec3(3)
    vec3 col = vec3(1,2,3);   // calls vec3(1,2,3)
}

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 882146

Yes, each invocation of the function is considered a separate call, with a (most likely) different result.

You can verify this with any function, such as with:

#include <iostream>

int getVal() {
    static int val = 0;
    return ++val;
}

int main() {
    std::cout << getVal() * getVal() * getVal() << '\n';
}

This will give you 1 * 2 * 3, or 6.

Upvotes: 2

Related Questions