Questions about the saved user ID

Wouldn't saving the effective user ID in a variable at the beginning of the program would make the saved user ID unnecessary?

It's not a question of what the userspace program remembers, but what rights the kernel lets it use. For the separation between users to work, it has to be system that controls what user IDs a process can use. Otherwise any process could just ask to become root.

How can I retrieve the saved user ID in a C program ? I was not able to find any functions doing that.

With standard functions you can't (there's only getuid() and geteuid()). At least Linux has getresuid() that return all three user IDs, though.

Anyway, usually you wouldn't need to read it. It's there to allow switching between the real user ID, and the effective user ID in case of a setuid program, so it starts as a copy of the effective user ID.

In a setuid program, the real user ID is that of the user running it, and the effective and saved user IDs are those of the user owning the program. The effective user ID is the one that matters for privilege checks, so if the process wants to temporarily drop privileges, it changes the effective user ID between the real and the saved user IDs.

In what way does the kernel use the saved user ID to check whether a process can or cannot change its user ID? Does this mean that when a process tries to change its effective user ID, the kernel checks the saved user ID to make sure, the process is allowed to do so?

Yes. The Linux man page for setuid() mentions this, but it's somewhat hidden:

ERRORS     
EPERM  The user is not privileged and uid does not match the real
       UID or saved set-user-ID of the calling process.

In other words, you can only set (the effective) user ID to one of the real or saved IDs.

The man page for setreuid() is clearer on that:

Unprivileged processes may only set the effective user ID to the real
user ID, the effective user ID, or the saved set-user-ID.