Given is a short Java function and I like to create a control flow graph for it but I'm not sure if it's fine like that? Because I left some things away such as variables that have already been created with the function together (int[] A, boolean[] boo).

boolean func(int[] A, boolean[] boo){
    boolean res;
    int n, leng;
    leng = A.length;
    n = 0;
    res = true;
    while(n < leng){
        if(A[n] <= 0 && !boo[n]){
            res = false;
    return res;

enter image description here

Link to the chart

Is it fine like that? Because in the test I write soon I would do it like that : /


Control flow graphs are usually not written with one statement per node, but divide the code into basic blocks that combine multiple statements. A basic block starts with a jump target and ends with a jump to another block. The jump at the end may be conditional.

Your control flow graph is generally correct, except

  • that it could be simplified by using basic blocks
  • that the n++ node has multiple outgoing jumps, but isn't a conditional statement. There must not be a direct jump from n++ to return res, instead there should only be the jump back to the while (...).
  • Thank you very much for your answer! I understand now that the edge from node 7 to node 8 must be removed because the only way to get to return aka node 8 is right after the termination of the while loop aka node 4. But I'm not sure about the simplification using basic blocks. How could this graph be made simplier? Maybe it's possible to remove the nodes 2 and 3 and keep everything else as it is? I think that should work because both variables i and leng are inside the while loop aka node 4? – roblind Jan 23 at 17:50
  • 1
    @roblind yes, in that control flow graph nodes 1,2,3 can be merged into a single block because there are only branches at the start and end – amon Jan 23 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.