r/C_Programming • • Sep 19 '26

Question List all possible sources of non-linear control flow in C

Some people believe C is a language where statements are executed sequentially and there is no magic control flow. This is false, but I just want to make sure I'm aware of all possible sources of non-obvious control flow. This is what I've got:

  1. Signal handlers. The kernel can choose any thread, interrupt it and make it run a signal handler. This can be mitigated by signal masks (for example, having a dedicated thread to handle signals and masking all signals on all other threads) but by default C is non-linear.
  2. longjmp. It interrupts the current call and maybe more calls, is not recoverable, does not perform any cleanup etc. And you have no control over it save for writing a setjmp yourself which still means your function gets interrupted. You could have a setjmp in every function to make 100% sure your control flow doesn't get hijacked, haha!
  3. Exceptions from other languages. If a C function is called from C++ and calls a C++ function and that throws an exception... This only affects mixed code bases, though.

Is there anything else? Can we be sure that without these three sources a C function evaluates in the order the C standard prescribes?

66 Upvotes

45 comments sorted by

6

u/torsten_dev Sep 19 '26

defer (TS 25755).

1

u/Linguistic-mystic Sep 20 '26

That's one of the reasons for my question, actually. What would be the things that break defer.

1

u/realhumanuser16234 Sep 20 '26

i think this issue is discussed in the ts

5

u/ern0plus4 Sep 19 '26

Interrupt handler on embedded platforms.

2

u/Linguistic-mystic Sep 20 '26

Interesting. But after the interrupt handler, the program execution resumes where it was stopped, right? All registers are restored and there is no stack unwinding etc?

2

u/qqqrrrs_ Sep 20 '26

It's the same with signal handlers

1

u/LargeSouth2432 Sep 22 '26

It might. What is being resumed depends on the scheduler (If existing).

11

u/MagicWolfEye Sep 19 '26

I'm not sure what you want to say with the longjmp

You say longjmp and it goes to the corresponding setjmp

4

u/Big-Rub9545 Sep 19 '26

In the sense that statements no longer execute in order (at least temporarily) while the program jumps to the point with setjmp.

8

u/mikeblas Sep 19 '26

Then we must also include conditionals, break, continue, and swtich.

→ More replies (2)

3

u/spellstrike Sep 19 '26 edited Sep 19 '26

reading from volatile variables related to hardware values that can change at any time?

really anything once you start dealing with an embedded system with error handling, callbacks, embedded multi threading stars to get to the point that it's no longer just doing a ordered list of commands

1

u/Linguistic-mystic Sep 20 '26

No, the control flow still follows source code, functions run to completion, so there's nothing non-linear here.

1

u/spellstrike Sep 21 '26 edited Sep 21 '26

running to completion is really assuming a few things instead of handling arbitrary real time input, errors, and systems that run at a lower ring that your software has insight into that don't interrupt the normal flow. get involved in some embedded system

47

u/josk613 Sep 19 '26

goto, atexit

41

u/OCROttawa Sep 19 '26

Your subject line talks about non-linear and then you ask for examples of non-obvious control flow. I would venture that these are not the same thing and neither is what you are asking about. The other comment I would make is that you need to differentiate the programming language “C” and the underlying system, be it an operating system or even bare metal.

“C” the language is by definition deterministic, it is not linear. If it was non-deterministic (whatever that means in this case) it would be very hard to program.

A loop is non-linear, a subroutine call is non-linear, both are deterministic and obvious. Have you ever looked at the way a case statement ends up when it is compiled into assembler, jumps all over the place.

You mention threads and kernels, these are operating system constructs. Signal/interrupt handlers are the same. Fork() is not a “C” construct it is an operating system call, if your OS doesn’t support fork() then the function will not exist.

Even things you are calling “non-linear”, like signal handlers are 100% deterministic.

There is nothing in the “C” language that is being violated by these “non-linear” operating system functions, if they were then the system would fall apart.

I guess the question still exists…what it is that you are trying to understand? Or what are you worrying about?

14

u/Interesting_Debate57 Sep 20 '26

Or as they say in the software engineering world, "what, exactly, is the problem that you're trying to solve?"

18

u/Dezgeg Sep 19 '26

Not in standard C but setcontext() and similar come to mind.

15

u/Cats_and_Shit Sep 19 '26 edited Sep 19 '26

You could have a setjmp in every function to make 100% sure your control flow doesn't get hijacked, haha!

This is incorrect. longjmp does not nececarily take you to the most recent setmp call, it takes you to the one that initialized the provided jmp_buf env argument.

1

u/flatfinger Sep 22 '26

If an institutional coding standard specifies how any functions that call longjmp will acquire the associated jmp_buf, that may allow a function to intercept any longjmp calls made by nested functions that follow the convention.

10

u/HugoNikanor Sep 19 '26

fork(2) (while technically not part of C) is interesting, since the following instructions are executed independently on two separate threads.

6

u/Big-Rub9545 Sep 19 '26

fork() doesn’t really interrupt linear execution, though. The parent and child processes both continue to execute instructions linearly.

3

u/ericonr Sep 19 '26

*two separate processes

3

u/der0hrwurm Sep 20 '26

The main source of non determinism in modern computers is we don’t know which of multiple processes will be picked up by the OS to execute next (unless you add some explicit check). The higher the clock frequency, the more non deterministic it gets.

7

u/Dangerous_Region1682 Sep 20 '26

Even in the days of single CPUs and non multithreaded kernels executing a fork() couldn’t always predict what the scheduler would execute next, the parent or the child, or even another process. That would been dependent on lots of things including the OS type and its scheduling algorithms.

These days with multithreaded kernels and multiple processor cores, your guess would be as good as mine. That, and clock frequency the OS scheduler uses, be it clock ticks or wall time, affects it too as you say.

Most software these days is in itself multithreaded using lightweight processes or similar constructs. If you want to be sure of correct concurrency, you have to handle the exclusion locking yourself with a language like C or use a language like Go which has its own features to support that.

I’m not quite sure what the OP means by deterministic. At the language level is one thing, but at the system level it’s another. These are usually timesharing systems where the determinism of user programs in some some level of meaning, can be but an illusion.

3

u/ByMeno Sep 19 '26

Unspecified evaluation order and short-circuiting can count i think ?

Edit: Maybe exit handlers too

3

u/TheThiefMaster Sep 19 '26

OS exceptions - e.g. Structured Exceptions on Windows

3

u/Cats_and_Shit Sep 19 '26 edited Sep 19 '26

Can we be sure that without these three sources a C function evaluates in the order the C standard prescribes?

Yes, but only on a technecicality, since the C standard does not prescribe any evaluation order.

The standard requires that externally visible operations, like interactions with files or volitile memory, occur as if a function was evaluated as a series of sequential statements. But neither your compiler nor you CPU will actually do that, because it would make things much, much slower.

3

u/flatfinger Sep 21 '26

But neither your compiler nor you CPU will actually do that, because it would make things much, much slower.

Many compilers intended for embedded programming treat programs as a sequence of steps, because the costs of doing so are for many tasks nowhere near as dire as some compiler writers claim.

2

u/actguru Sep 19 '26

There are compiler extensions like GCC __attribute__((cleanup(function_name))) that cause scope related execution.

2

u/wiskinator Sep 19 '26

Not just signal handlers but interrupt handlers too.

2

u/sciencekm Sep 20 '26

Overrun your stack and the function returns somewhere else (assuming it does not outright crash).

3

u/duane11583 Sep 19 '26

As a language The c language does not allow non linear flow

Your example of a signal handler is misleading. When the signal is delivered it starts at the function entry point 

And setjmp longjmp is just an extra return with nonzero return value but it otherwise uses the same control flow

What would be non linearity could occur during a stack over flow where the return address gets clobbered and the code returns somewhere in expected but then the code would continue in a linear fashion

At some basic level the cpu is executing the next code in a linear (one after another) way

So I’m not following what you mean

0

u/yel50 Sep 19 '26

by your logic, all control flow is linear and the concept of nonlinear flow doesn't exist. things like call/cc in scheme, algebraic effects, exception handling, etc are still sequential at the hardware level.

 So I’m not following what you mean

linear flow means the code executes in the order it's written in the source code. nonlinear means it jumps around in an unstructured way. c is generally considered to be linear, but there are ways to achieve nonlinear flows.

2

u/duane11583 Sep 19 '26

I do not know of a language or cpu what you describe

2

u/Motor_Let_6190 Sep 20 '26

Since at least the 90s, with pipeline architecture you  haven't had fully predictable code flow. Imagine with multi threaded multicore CPUs...  Plus compiler optimizations, etc.  Not sure what you're on about with the language semantics aspect of things when using standard toolchain and hardware means your point is DOA.  What the CPU executes is assembly opcodes and data, running on a micro architecture specific to the particular ISA vendor (for example for x64, underneath the assembly Intel and AMD have very different micro architectures)

Or am I misunderstanding your point? Cheers !

0

u/Daveinatx Sep 19 '26

switch , goto are implicit non linear contro

Edit: bin-linear refers to where eip/pc can be modified away from the next logical instruction.

3

u/duane11583 Sep 19 '26

a for loop, is just a combination of an if and a goto. same with a switch.

so everything is non linear.

1

u/duane11583 Sep 20 '26

if the eip/ip does not go to a deterministic place there is a problem.

for example you could permute

effectively (encode/encrypt) the address signals this would be doable but not very helpful or usable

2

u/maep Sep 19 '26

All guarantees go out the window when you invoke undefined behavior.

1

u/flatfinger Sep 21 '26

Or if you rely upon corner cases whose behavior is defined by the Standard but which compiler writers find inconvenient, like the italicized portion of N1570 6.5.9p6:

Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.

Both clang and gcc are prone to make inconsistent assumptions if code would compare pointers like those described in the italicized case above, despite the fact that the Standard very explicitly specified behavior in that corner case.

1

u/realdreamer1993 Sep 20 '26

there is hierarchy, and our program/process is owned by other entity.
So the entity usually have some ways to intervense our process...but still we 99% focus on the C source code.
We don't care/program the other entity except on the boundary/contract.

1

u/TheOtherBorgCube Sep 20 '26

Threads since C11 https://en.cppreference.com/c/header/threads
Various thread libraries before then.

thrd_create might be entirely deterministic in terms of you call it, it returns.

But the side-effect is that now you have something else going on in some parallel fashion with your current code.

1

u/burlingk Sep 20 '26

C programs are pretty much assumed to be built with if then and switch statements.

So whoever you're talking to probably needs to study, at all... Because more would imply the already tried.