0

I wrote this code to test static_assert

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <inttypes.h>

#define static_assert _Static_assert

typedef enum {ONE=1, TWO, THREE} num_t;

uint8_t Is_Num_Valid(num_t number){
uint8_t i = 0;
    for(i=1;i<4;i++){
        if(number == i){
            return 1;
        }
    }
    return 0;
}

int main()
{
    num_t number;
    number = ONE;
    printf("%d\n", Is_Num_Valid(number));

    if(Is_Num_Valid(number)){
        static_assert(0, "Number entered is out of boundaries");
    }


    printf("Number is> %d\n", number);
    return 0;
}

Which always results in a compilation error error: static assertion failed: "Number entered is out of boundaries"

why this is not working, it should not execute the body of if() if the condition is 0!!!

  • i know i can't use a const int with static_assert as it's != constant_expression, thats why i tried to use this method. – Ahmed Osama Dec 15 '18 at 11:43
  • What do you expect if it is not valid? Do you expect a compilation error after successful compilation? – L. F. Dec 15 '18 at 11:55
  • If you need to evaluate expression at runtime, perhaps you wanted ordinary `assert`, not `static` one? `static_assert(0)` basically instructs compiler to always fail compilation of current translation unit, regardless of where it placed (unless cut out by e.g. preprocessor's `#if`). – keltar Dec 15 '18 at 12:01
  • thanks guys for help, i already know the difference between assert and static_assert, but the answer of Daniel H clarified what is happening. – Ahmed Osama Dec 15 '18 at 12:32

1 Answers1

0

A static_assert happens at compile time, but the decision in an if statement happens at run time. The compiler cannot know that the if clause will be false, and it needs to look at the body of the if statement to know what to do if it isn’t. It sees a static assert, which fails, so generates a compilation error.

Daniel H
  • 7,223
  • 2
  • 26
  • 41