C programming language quirks


In my UG days, I spent a lot of time with the C programming language. Had forgotten most of it.

But now (Feb 2023) I'm a TA for a lab course using C. Noting down stuff that I came across again..


No evaluation within sizeof

#include<stdio.h>

int main() {
    int a=3, b;
    b = sizeof(a=10);
    printf("a=%d, b=%d\n", a, b);
    // a=3, b=4

    // Value of b is compiler/arch dependent though.

    return 0;
}

(Thanks to Kevin for telling me this.)

Expression inside sizeof is not evaluated. So the value of a never changed.

In sizeof(a=10), type of a=10 is looked at. It is found to be int. So essentially, it is same as saying sizeof(int) or sizeof(10), I guess.

sizeof(int) is usually 4, but can be different depending on architecture and compiler.

Multiple sequence points

Multiple sequence points => undefined behaviour.

#include<stdio.h>

int main() {
    int a=3;
    printf("%d\n", a++ + ++a);
    // 8

    // Needn't be so though. It's undefined behaviour.

    return 0; 
}

Evaluation could be like:

(Thanks to Kevin for reminding me about this.)

Calling main from main

Looks like this is possible in C (gcc).

#include<stdio.h>

int ctr = 5;

int main() {
    if(ctr>0) {
        printf("Hi\n");
        ctr--;
        main();
    }
}

/*
Hi
Hi
Hi
Hi
Hi
*/

Apparently, C++ standard prohibits this but gcc allows it.

CPP