Sounds dreadful. I personally would very much dislike your teacher.
1 2 3 4 5
|
int q=5;
for (q=-2; q=-5; q+=3) { //assignment in condition part??
printf("%d",q); //prints -5
break;
}
| |
A for loop works like this:
for (initialization; condition; iteration) { }
First, the initialization happens. Then, the condition is checked. If the condition evaluates to false, the inside of the loop is not entered. Otherwise, the inside of the loop is entered.
In your example, your initialization set q to be -2, but then your condition sets q to be -5.
Any non-zero value in C or C++ is evaluated to be true. So you're loop is entered with q being -5.
1 2 3 4 5
|
int d[][3][2]={4,5,6,7,8,9,10,11,12,13,14,15,16};
int i=-1;
int j;
j=d[i++][++i][++i];
printf("%d",j); //prints 4?? why j=d[0][0][0] ?
| |
First, look at something simpler.
int d[3] = {1};
This will make an array initialized with the first element being 1, and the 2nd and last element being 0.
int d[] = {3, 4};
This will make an array of size 2, with the elements in it being initialized to 3 and 4.
int d[2][2] = {1, 2, 3, 4};
Is valid, and equivalent to doing
int d[2][2] = { {1, 2}, {3, 4} };
When you don't give the size of the outer-most array, the size of the array will become the minimum possible to hold the values that you supply it with in the initialization.
In your example, let's look at the initialization of the array. The outer-most dimension of the array is not given, but the inner-two dimensions are 3 and 2. This means that the total size of the array will be a multiple of 6, and this also means that the outer-most dimension's size will be the number of elements you initialized it with, divided by (3*2).
{4,5,6,7,8,9,10,11,12,13,14,15,16}
becomes equivalent to
1 2 3
|
{ { {4,5}, {6,7}, {8,9} },
{ {10,11},{12,13}, {14,15} },
{ {16,0}, {0,0} , {0,0} } };
| |
j=d[i++][++i][++i];
This, simply put, is undefined behavior. You are trying to increment i three times within one sequence point. There's no point trying to make sense of this part of the code, because you simply have undefined behavior. It's not clever,
it's just wrong. In general, avoid ever using i++ at the same time as you reference i in a different place on the same line.
It sounds like you want more examples beyond what you were given. I don't know the scope of your exam, but function pointers have one hell of a messy syntax if you want to look into that.
https://www.geeksforgeeks.org/function-pointer-in-c/