user1086516
user1086516

Reputation: 877

About data types with for loops with commas

In C if you have the following code:

for (size_t x, y = someValue; y > 0; y -= x, ptr1 += x, ptr2 += x) 
{
        // do stuff
} 

Will the variable y also be of the type size_t or would it be an int?

Upvotes: 0

Views: 90

Answers (5)

Soren
Soren

Reputation: 14708

a declaration of

int a,b,c;
size_t x,y,z;

means that all of a,b,c are same type (int) as are x,y,z (size_t)

The declaration inside a for-loop is no different -- and in your example both x and y are of type size_t

however in your example x is not initialized (only y is set to somevalue) -- and unless the body of the loops set it to something you will find that y -= x is going to give you random undefined results.

Upvotes: 5

paulsm4
paulsm4

Reputation: 121799

for (size_t x, y = someValue; y > 0; y -= x, ptr1 += x, ptr2 += x) 
    {
            // do stuff
    } 
  1. x and y are both "size_t" (usually 4 bytes on most platforms)

  2. y is initialized to "someValue".

  3. x, however, is UNINITIALIZED.

int main (int argc, char *argv[]) {
size_t x, y = 1;
printf ("x=%d, y=%d, sizeof(x)=%d...\n", x, y, sizeof (x));
return 0; }

x=4201366, y=1, sizeof(x)=4...

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124722

In your example yes; x and y are both of type size_t. However, to add to your confusing, consider declaration:

int *x, y;

In this case x is a pointer to int, but y is just a int.

Upvotes: 0

AusCBloke
AusCBloke

Reputation: 18502

y would be the same time as x, size_t, just as it would with the same expression outside of a for loop:

size_t x, y = someValue;

One simple way to find out is to just print the size of the variables for yourself, as long as sizeof(size_t) != sizeof(int) (if it is, just change size_t to char to make the difference evident).

Upvotes: 0

Dan
Dan

Reputation: 10786

It's just the same as if you do:

size_t x, y = someValue;

In such situation both x and y are size_t and y = someValue.

Upvotes: 0

Related Questions